Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional terms in Python list initialization

I want to do something like this:

a = some_funct()
b = [ 1, a if a is not None ]

The list b should be one element long if a is None, and two elements long if a is not None. Is this possible in Python or do I have to use a separate if check followed by add()?

like image 754
A_K Avatar asked Nov 18 '16 03:11

A_K


2 Answers

Doesn't look the best, but you could do

b = [1] + ([a] if a is not None else [])

Of course, it would be better to check as it increases code readability.

like image 113
toblerone_country Avatar answered Sep 24 '22 03:09

toblerone_country


You can do this using list comprehension

b = [x for x in (1, a) if x is not None]

The tuple (1, a) is the total set, b will become a list of all elements in that total set which are not None

like image 25
Anthony Oteri Avatar answered Sep 22 '22 03:09

Anthony Oteri