Conditional Terms in Python List Initialization

I want to do something like this:

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

List b must be one long element if a is None, and two elements are long if a is not None. Is this possible in Python, or do I need to use a separate one if I check and then add ()?

+4
source share
4 answers

Doesn't look better, but you could do

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

Of course, it would be better to check how this improves code readability.

+3
source
a = some_funct()
b = [ 1, a ] if a is not None else [1]
+2
source

,

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

(1, a) - , b , None

+1

I relate to this game too late, but I had the same question, and, seeing other answers, I came up with this solution using sets:

list({1, a or 1})
+1
source

Source: https://habr.com/ru/post/1661136/


All Articles