Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python ternary operator can't return multiple values?

Tags:

python

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?

like image 649
Valdogg21 Avatar asked Jul 12 '13 19:07

Valdogg21


Video Answer


1 Answers

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)
like image 112
tckmn Avatar answered Oct 14 '22 10:10

tckmn