Search code examples
pythonfor-looptuplesiterable-unpacking

Unpacking a sequence structure using a `for` loop statement in Python


I am having a problem understanding why the following cannot be unpacked in the header line of a for loop.

Given that:

>>> (a,b),c = (1,2),3
>>> a
1
>>> b
2
>>> c
3

Why when I then do this do I receive an error?:

for (a,b),c in [(1,2),3]:
...    print(a,b,c)

I am aware of how to get it working, as the following gives me the desired result:

>>> for (a,b),c in [((1,2),3)]:
...    print(a,b,c)
1 2 3

But why is an extra parenthesis enclosing the original object in the header line of the for loop required to achieve this output?

Given that any sequence can be unpacked [(1,2), 3] is syntactically correct as a list sequence, and should theoretically be able to be assigned to the target variables (a,b),c. So why is this not the case and why do I have to enclose the sequence with an additional parenthesis?

Some clarity around this would be greatly appreciated.


Solution

  • The for loop is iterating over the list entries, so the first time it tries to assign (1,2) to (a,b),c, which won't work. Adding the extra parentheses converts (1,2),3 into a tuple which is a single list entry ((1,2),3) to assign to (a,b),c the first time the for loop iterates, which works.

    Try:

    for v in [(1,2),3]:
       print v
    

    And you will see that v is assigned (1,2), then 3.