Search code examples
pythonpython-3.xtuplesiterable-unpacking

How to unpack a list of tuples with enumerate?


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.


Solution

  • 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.