-1

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
Martín Nieva
  • 476
  • 1
  • 5
  • 13

2 Answers2

3

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.

chepner
  • 497,756
  • 71
  • 530
  • 681
  • Ohhh. Thank you. So why does "for a, b in [0, 1, 2, 3, 4, 5]: print(a); print(b)" throw an exception? "TypeError: 'int' object is not iterable" – Martín Nieva Jul 09 '19 at 02:32
  • For the same reason `a, b = 0` would throw the same error. You can't extract multiple items from the *iterable* in a `for` loop, and the new example is a list of ints, not a list of (iterable) tuples. – chepner Jul 09 '19 at 12:21
0

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.

guorui
  • 871
  • 2
  • 9
  • 21