Search code examples
pythonif-statementiterable-unpacking

q, w = 1, 2 if 1 < 2 else 2, 1; ValueError: too many values to unpack. Why?


As stated in the title

q, w = 1, 2 if 1 < 2 else 2, 1
ValueError: too many values to unpack

What's going on here??


Solution

  • If you inspect

    1, 2 if 1 < 2 else 2, 1
    

    then you see that python will interpret it like

    (1, 2 if 1 < 2 else 2) , 1
    

    and you will end up with (1, 2, 1) which contains too much values for 2 variables of q, w

    Because python accepts first comma after conditional (1 < 2) as the end of single line if-else statement and append after-the-comma section to the resulting value set.

    A parenthesis at the last value set will be enough

    q, w = 1, 2 if 1 < 2 else (2, 1)
    

    But it would definitely be better to use parenthesis for both

    q, w = (1, 2) if 1 < 2 else (2, 1)