13

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.

Ajax1234
  • 69,937
  • 8
  • 61
  • 102
Finn
  • 1,999
  • 2
  • 24
  • 29

2 Answers2

31

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.

Ajax1234
  • 69,937
  • 8
  • 61
  • 102
7

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.

Alexander
  • 105,104
  • 32
  • 201
  • 196