I know it's frowned upon by some, but I like using Python's ternary operator, as it makes simple if
/else
statements cleaner to read (I think). In any event, I've found that I can't do this:
>>> a,b = 1,2 if True else 0,0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: too many values to unpack
The way I figured the ternary operator works is that it essentially builds the following:
if True:
a,b = 1,2
else:
a,b = 0,0
Could someone explain why my first code sample doesn't work? And, if there is one, provide a one-liner to assign multiple variables conditionally?
It's parsing that as three values, which are:
1,
2 if True else 0,
0
Therefore it becomes three values (1,2,0
), which is more than the two values on the left side of the expression.
Try:
a,b = (1,2) if True else (0,0)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With