Unpacking list of tuples

idetyp :

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!

quamrana :

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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=404729&siteId=1