1

Here is the code:

for m, n in ("example_string", True):
    print(m, n)

This code doesn't work. Interpreter says: enter image description here

But how to unpack this 2-items tuple in FOR loop?

Desirable output is:

example_string True

Alec
  • 8,529
  • 8
  • 37
  • 63
Quanti Monati
  • 769
  • 1
  • 11
  • 35

2 Answers2

4

You need to unpack it first.

m, n = ("example_string", True)

If the tuple contained iterables itself, then you could unpack it in the loop:

for m, n in (('x','y'), (x,y)):  # this works
Alec
  • 8,529
  • 8
  • 37
  • 63
2

You can't iterate over a 2-length tuple and unpack it into a tuple at the same time. Try this:

m, n  = ("example_string", True)
print(m, n)

If you want to unpack your tuple inside the for-loop, each item in the iterable must be a 2-tuple.

for m,n in [(1,2), (3,4)]:
    print(m,n)

This would print:

1 2
3 4
rdas
  • 20,604
  • 6
  • 33
  • 46