Search code examples
pythonpython-3.xpython-2.7iterable-unpacking

Cannot unpack tuple object in FOR loop Python


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


Solution

  • 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