[python] Tuple unpacking in for loops

I stumbled across the following code:

for i,a in enumerate(attributes):
   labels.append(Label(root, text = a, justify = LEFT).grid(sticky = W))
   e = Entry(root)
   e.grid(column=1, row=i)
   entries.append(e)
   entries[i].insert(INSERT,"text to insert")

I don't understand the 'i,a' bit and searching google for information on 'for' is a pain in the bum and when I try and experement with the code I get the error:

ValueError: need more than 1 value to unpack

Does anyone know what it does or something to do with it that I can google to learn more?

This question is related to python python-3.x

The answer is


[i for i in enumerate(['a','b','c'])]

Result:

[(0, 'a'), (1, 'b'), (2, 'c')]

Take this code as an example:

elements = ['a', 'b', 'c', 'd', 'e']
index = 0

for element in elements:
  print element, index
  index += 1

You loop over the list and store an index variable as well. enumerate() does the same thing, but more concisely:

elements = ['a', 'b', 'c', 'd', 'e']

for index, element in enumerate(elements):
  print element, index

The index, element notation is required because enumerate returns a tuple ((1, 'a'), (2, 'b'), ...) that is unpacked into two different variables.


The enumerate function returns a generator object which, at each iteration, yields a tuple containing the index of the element (i), numbered starting from 0 by default, coupled with the element itself (a), and the for loop conveniently allows you to access both fields of those generated tuples and assign variable names to them.


Short answer, unpacking tuples from a list in a for loop works. enumerate() creates a tuple using the current index and the entire current item, such as (0, ('bob', 3))

I created some test code to demonstrate this:

    list = [('bob', 3), ('alice', 0), ('john', 5), ('chris', 4), ('alex', 2)]

    print("Displaying Enumerated List")
    for name, num in enumerate(list):
        print("{0}: {1}".format(name, num))

    print("Display Normal Iteration though List")
    for name, num in list:
        print("{0}: {1}".format(name, num))

The simplicity of Tuple unpacking is probably one of my favourite things about Python :D


Enumerate basically gives you an index to work with in the for loop. So:

for i,a in enumerate([4, 5, 6, 7]):
    print i, ": ", a

Would print:

0: 4
1: 5
2: 6
3: 7