xgeniux
xgeniux

Reputation: 49

why can't I print a single tuple from a list?

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)

Upvotes: 2

Views: 350

Answers (4)

Attila Bognár
Attila Bognár

Reputation: 192

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)

Upvotes: 1

Filip Młynarski
Filip Młynarski

Reputation: 3612

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)

Upvotes: 3

Daniel Roseman
Daniel Roseman

Reputation: 599630

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)

Upvotes: 0

user2201041
user2201041

Reputation:

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.

Upvotes: 4

Related Questions