Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's going on in this code?

x,y,z = [1,2,3], [4,5,6], [7,8,9]
for a,b,c in x,y,z:
    print(a,b,c)

The output is :

1 2 3
4 5 6
7 8 9

I can't mentally navigate whatever logic is going on here to produce this output. I am aware of the zip function to make this code behave in the way I clearly intend it to; but I'm just trying to understand why it works this way when you don't use the zip function.

Is this a deliberate functionality, a feature, that you can successively iterate through multiple lists this way? Sort of?

like image 704
temporary_user_name Avatar asked Oct 16 '13 04:10

temporary_user_name


2 Answers

You have good answers already, but I think considering this equivalent variation will help to make it clearer:

x,y,z = [1,2,3], [4,5,6], [7,8,9]
for t in x,y,z:
    a, b, c = t
    print(a,b,c)

You're not surprised that t is successively bound to x, y and z, right? Exactly the same thing is happening in your original code, except that the:

a, b, c = t

part isn't as obvious.

like image 62
Tim Peters Avatar answered Sep 28 '22 10:09

Tim Peters


Oh man this is a mess. This is simply too much use of python's iterable unpacking. The statement a, b, c = iterable simply assigns the elements of iterable to the variables a, b, and c. In this case iterable must have 3 elements.

First you have:

x,y,z = [1,2,3], [4,5,6], [7,8,9]
# Which is:
x = [1, 2, 3]
y = [4, 5, 6]
z = [7, 8, 9]

then you have:

for a, b, c in x, y, z:
    print(a, b, c)
# Which is:
temp = (x, y, z)
for item in temp:
    a = item[0]
    b = item[1]
    c = item[2]
    print(a, b, c)

One more thing to note is that the statement mytuple = 1, 2, 3 is the same as mytuple = (1, 2, 3).

like image 41
Bi Rico Avatar answered Sep 28 '22 09:09

Bi Rico