Search code examples
pythonpython-3.xconditional-operator

Too many values to unpack in ternary operator


Why in the second line of below code snippet of ternary operator there are 3 values to unpack, I am expecting it to be 2:

x,y=5,10
x,y=100,20 if x<5 else 30,40
print(x,y)

Output: ValueError: too many values to unpack (expected 2)

x,y=5,10
x,y,z=100,20 if x<5 else 30,40
print(x,y,z)

Output: 100 30 40


Solution

  • What you are writing is the following:

    x, y = (100), (20 if x < 5 else 30), (40)
    

    You are missing some parenthesis. Python can't determine automatically what is a tuple and what isn't. What you actually want to do is this:

    x, y = (100, 20) if x < 5 else (30, 40)