Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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 a more specific term associated with it that I can google to learn more?

like image 722
Talisin Avatar asked Jun 03 '12 04:06

Talisin


People also ask

How do I unpack a tuple in a for loop?

Unpack a Tuple in a for Loop in PythonThe number of variables on the left side or before the equals sign should equal the length of the tuple or the list. For example, if a tuple has 5 elements, then the code to unpack it would be as follows. We can use the same syntax to unpack values within a for loop.

Is unpacking possible in a tuple?

In python tuples can be unpacked using a function in function tuple is passed and in function, values are unpacked into a normal variable. The following code explains how to deal with an arbitrary number of arguments. “*_” is used to specify the arbitrary number of arguments in the tuple.

What is unpacking of a tuple?

Unpacking a tuple means splitting the tuple's elements into individual variables. For example: x, y = (1, 2) Code language: Python (python)

Can you for loop A tuple?

You can loop through the tuple items by using a for loop.


2 Answers

You could google "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.

like image 117
BrenBarn Avatar answered Oct 17 '22 08:10

BrenBarn


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 
like image 42
nathancahill Avatar answered Oct 17 '22 06:10

nathancahill