Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unpack a list of tuples with enumerate? [duplicate]

I stumbled upon an unpack issue I can not explain.

This works:

tuples = [('Jhon', 1), ('Jane', 2)]

for name, score in tuples:
    ...

This also works

for id, entry in enumerate(tuples):
    name, score = entry
    ...

but this does not work:

for id, name, score in enumerate(tuples):
    ...

throwing a ValueError: need more than 2 values to unpack exeption.

like image 928
Finn Avatar asked Aug 18 '17 15:08

Finn


2 Answers

enumerate itself creates tuples with the list value and its corresponding index. In this case:

list(enumerate(tuples))

gives:

[(0, ('Jhon', 1)), (1, ('Jane', 2))]

To fully unpack you can try this:

for index, (name, id) in enumerate(tuples):
     pass

Here, Python is paring the index and tuple object on the right side with the results on the left side, and then assigning.

like image 55
Ajax1234 Avatar answered Oct 05 '22 23:10

Ajax1234


Wrap name and score in a tuple when unpacking.

for id, (name, score) in enumerate(tuples):
    print(id, name, score)

# Output
# (0, 'Jhon', 1)
# (1, 'Jane', 2)

enumerate(thing), where thing is either an iterator or a sequence, returns a iterator that will return (0, thing[0]), (1, thing[1]), (2, thing[2]), and so forth.

In this case, thing is a tuple.

like image 40
Alexander Avatar answered Oct 05 '22 22:10

Alexander