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
CodePudding user response:
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)