morfys morfys - 4 months ago 23
Python Question

list comprehension where list itself is None

Is there a way for me to deal with the case where the list my_list itself can be None in
the list comprehension:

[x for x in my_list]


I tried this:

[x for x in my_list if my_list is not None else ['1']]


However, it doesn't seem to work.

Answer

I think this does what you want:

>>> my_list = None
>>> [x for x in my_list] if my_list is not None else ['1']
['1']

The change here is moving the ternary statement outside of the list comprehension.

Alternatively, if we add some parens, we can keep the ternary statement inside the list comprehension:

>>> my_list = None
>>> [x for x in (my_list if my_list is not None else ['1'])]
['1']
Comments