Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to shorten appending to different lists depending on the outcome of if statement

Any idea if it's possible to shorten and prettify this one (an extra variant assumes nested if-else conditions and more lists)?

some_list, some_other_list = [], []
if condition:
    some_list.append(value)
else:
    some_other_list.append(value)
like image 444
foxale Avatar asked Apr 02 '19 10:04

foxale


1 Answers

Ternary expression:

(some_list if condition else some_other_list).append(value)

Explanation:

>>> condition = True
>>> ("A" if condition else "B")
A

>>> condition = False
>>> ("A" if condition else "B")
B
like image 62
meowgoesthedog Avatar answered Oct 01 '22 17:10

meowgoesthedog