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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With