Gopinath S
Gopinath S

Reputation: 561

Python one line if statement with two actions

I am trying to find a way to get two actions done in one line if statement, I can find a lot of answers to perform a single action in if statement one-liner but not for this. Is it even possible? I tried something like this but failed with ValueError - too many values to unpack (expected 2). Thanks.

g, er = "id", "err" if no_of_errs <= 1 else "ppd", "ers"

Upvotes: 2

Views: 4087

Answers (1)

Patrick Artner
Patrick Artner

Reputation: 51653

Python is looking at your code like this:

 g, er = ( "id" )  ,  ( "err" if no_of_errs <= 1 else "ppd" )   , ( "ers" )

3 things to unpack, only 2 to pack it into.

The reason behind the error is operator priority, you can either read lots of lenghty text here or google it and find a table like here.


Fix it by makeing the tuples explicit with parenthesis:

no_of_errs = 0
g, er = ("id", "err") if no_of_errs <= 1 else ("ppd", "ers")
print(g,er)

no_of_errs = 10
g, er = ("id", "err") if no_of_errs <= 1 else ("ppd", "ers")
print(g,er)

Output:

id err
ppd ers

With explicit tuples, no more operator confusion and it works.


Keywords for google: operator priority precedence or smth alike

Upvotes: 6

Related Questions