I got confused with some for loop statement. I can't figure out what exactly does it do.
for a, b in [(0, 1), (2, 3), (4, 5)]:
print(a)
print(b)
I coudn't expect any output.
The output is
0
1
2
3
4
5
I got confused with some for loop statement. I can't figure out what exactly does it do.
for a, b in [(0, 1), (2, 3), (4, 5)]:
print(a)
print(b)
I coudn't expect any output.
The output is
0
1
2
3
4
5
It's tuple unpacking, just like in an assignment statement. It's a shorter way of writing
for t in [(0, 1), (2, 3), (4, 5)]:
a, b = t
print(a)
print(b)
Instead of assigning each tuple to t
, then unpacking t
into a
and b
, each tuple is unpacked directly to a
and b
by the for
loop.
This means:
step 1: a, b = (0, 1)
, so print(a)
will produce 0
and print(b)
will produce 1
.
step 2: a, b = (2, 3)
, so print(a)
will produce 2
and print(b)
will produce 3
.
step 3: a, b = (4, 5)
, so print(a)
will produce 4
and print(b)
will produce 5
.