Reputation: 626
I was surprised today by the following code:
testcases = [([1, 1, 1], 2, 2)]
for a, b, c in testcases:
print(a, b, c)
it prints:
[1, 1, 1] 2 2
I expected an error and thought we'd need a second loop to get to tuples' elements. Could enyone explain to me how it works? I don't get how a
, b
and c
are assigned. I used Python 3.6. Cheers!
Upvotes: 4
Views: 2005
Reputation: 328
During the unpacking of tuple, the total number of variables on the left-hand side should be equivalent to the total number of values in given tuple. Python gives the syntax to pass optional arguments (*arguments) for tuple unpacking of arbitrary length. All values will be assigned to every variable in the order of their specification and all remaining values will be assigned to *arguments .For example,
>>> tup = ("Elem1", "Elem2","Elem3","Elem4","Unpacking a tuple")
>>> (unp1,*unp2, unp3) = tup
>>> print(*unp2)
Elem2 Elem3 Elem4
>>> print(unp1)
Elem1
>>> print(unp3)
Unpacking a tuple
>>> print(type(unp1),type(unp3))
<class 'str'> <class 'str'>
>>> print(type(unp2))
<class 'list'>
What’s happening at a lower level is that we’re creating a tuple of 5 elements and then looping over that tuple and taking each of the five items we get from looping and assigning them to three variables on the left hand side in order. Hope this helps.
Upvotes: 0
Reputation: 39414
Let's look at what you have:
testcases = [([1, 1, 1], 2, 2)]
This is a list. Of size one. So testcases[0]
is the only element there is.
So this code:
for a, b, c in testcases:
pass
is a loop of length one. So each time through the loop (that is just the once), you get the element: ([1, 1, 1], 2, 2)
which is a tuple
. Of size three.
So unpacking that: a,b,c = testcases[0]
gives:
a == [1, 1, 1]
b == 2
c == 2
which is what you see printed.
Upvotes: 7