Unpacking a tuple into a loop

I am having trouble unpacking tuples. In particular, I don't know why this doesn't work:

a = [0,1,2,3]
b = [4,5,6,7]
p = a,b

for i,k in p:
    print i,k

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-422-2ba96d641daa> in <module>()
----> 1 for i,k in p:
  2     print i,k
  3 

ValueError: too many values to unpack

      

It seems to me that the above code should unpack the two lists in a tuple p

on i

and k

, but this is clearly not what is happening and I'm not sure why.

So, I have two questions:

  • What does for i,k in p

    it actually do if it doesn't unpack the lists in a tuple
  • How easy is it to unpack lists from a tuple in a for loop?

Expected Result:

[0,1,2,3]
[4,5,6,7]

      

I am using python 2.7.9 in case it is version specific.

+3


source to share


2 answers


If you step by step ...

First, by doing p = a, b

, you will get a tuple of exactly 2 elements - your lists:

>>> a = [0, 1, 2, 3]
>>> b = [4, 5, 6, 7]
>>> p = a, b
>>> print p
([0,1,2,3], [4, 5, 6, 7])

      

Then, when you execute for i, k in p

, Python will try to get the first element inside p

and then unpack it into i, k. So the first iteration of your loop basically does something equivalent to this:

>>> temp = p[0]
>>> print temp
[0, 1, 2, 3]
>>> i, j = temp
Traceback (most recent call last):
  File "<stdin>", line 1 in <module>
ValueError: too many values to unpack

      

It won't work as basically you are trying to do this i, k = [0, 1, 2, 3]

and there are more items in the list then there are variables.

You can use zip instead , which concatenates the numbers inside both lists.

For example:

>>> p = zip(a, b)
>>> print p
[(0, 4), (1, 5), (2, 6), (3, 7)]

      

This way, when we run your loop, the number of items inside the first tuple matches the number of variables in your loop, so Python won't throw an error. This means your result will be as follows:



0 4
1 5
2 6
3 7

      

If this is not your desired output, then you need to rethink the structure of your code.


Edit:

Based on your update, if you just want your output to be:

[0, 1, 2, 3]
[4, 5, 6, 7]

      

... then you don't need to use unpacking at all. The following loop will work very well:

for i in p:
    print i

      

i

will be assigned to the first element inside p

in the first iteration, and then to the second element when the loop repeats.

+14


source


p (a,b)

.

Since you are iterating through it with a for loop, you get each element in the tuple one at a time:



for x in p:

assigns ax, then b - x. In this case, your x is i,k

. Both a and b are lists of 4 elements, so they cannot be assigned to two elements. You can do for i,j,k,l in p

that will give you four elements in different variables.

This, however, will work: i, k = p

since p is a two-tuple.

+3


source







All Articles