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
  • 7,110
  • 7
  • 28
  • 53
Quanti Monati
  • 749
  • 1
  • 7
  • 30

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
  • 7,110
  • 7
  • 28
  • 53
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
  • 18,048
  • 6
  • 31
  • 42