2

I'm just trying to flip and print the first tuple in a list. If I try this code I get error "cannot unpack non-iterable int object"

lst = [('a',1),('b',2),('c',3)]
for x,y in lst[0]:
    print(y,x)

However if I make this simple edit, it works fine. why can't I print a single tuple from a list?

lst = [('a',1),('b',2),('c',3)]
for x,y in lst[:1]:
    print(y,x)
slider
  • 12,810
  • 1
  • 26
  • 42
xgeniux
  • 49
  • 5

4 Answers4

4

Your list:

lst = [('a',1),('b',2),('c',3)]

The first element of the list:

>>> lst[0]
(1, 'a')

Then when you iterate over this, you are asking to unpack each element. It would be like writing

for x, y in 1:
    # do something
for x, y in 'a':
    # do something

Wth lst[:1], you are slicing the list, and getting a list of tuples back.

3

Easiest way to flip first element would be to:

lst = [('a',1),('b',2),('c',3)]
print((lst[0][1], lst[0][0])) # -> (1, 'a')

However reason why your code throws error here is because you try to iterate over element instead of list, where element is ('a',1) by iterating over it first value is 'a' and you try to split it into 2 variables x and y which throws an error.

print(type(lst[0])) # -> <class 'tuple'>
for x,y in lst[0]:
    print(y,x)

Here if we iterate over list [('a',1)] (because we used slice as list index instead of integer) first value is indeed ('a',1) and we can split it into x and y variables without errors.

print(type(lst[:1])) # -> <class 'list'>
for x,y in lst[:1]:
    print(y,x)
Filip Młynarski
  • 3,534
  • 1
  • 10
  • 22
1

You are trying to loop through the first element of the list. Just unzip the first element and print:

x, y = lst[0]
print(y,x)

or in a loop:

for x, y in lst:
    print(y, x)
handras
  • 1,548
  • 14
  • 28
0

You don't want a loop there. lst[0] is the tuple you want to flip, there is no need to iterate.

x, y = lst[0]
print(y, X)
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895