Tuple unpacking in for loops

65

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 tagged with python python-3.x

~ Asked on 2012-06-03 04:24:10

The Best Answer is


126

You could google on "tuple unpacking". This can be used in various places in Python. The simplest is in assignment

>>> x = (1,2)
>>> a, b = x
>>> a
1
>>> b
2

In a for loop it works similarly. If each element of the iterable is a tuple, then you can specify two variables and each element in the loop will be unpacked to the two.

>>> x = [(1,2), (3,4), (5,6)]
>>> for item in x:
...     print "A tuple", item
A tuple (1, 2)
A tuple (3, 4)
A tuple (5, 6)
>>> for a, b in x:
...     print "First", a, "then", b
First 1 then 2
First 3 then 4
First 5 then 6

The enumerate function creates an iterable of tuples, so it can be used this way.

~ Answered on 2012-06-03 04:27:54


21

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

~ Answered on 2012-06-03 04:29:13


Most Viewed Questions: