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?
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.
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)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With