Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 576
morfys Avatar asked Dec 11 '22 16:12

morfys


2 Answers

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']
like image 137
John1024 Avatar answered Dec 23 '22 04:12

John1024


Your code is equivalent to making a copy of the list if it is not None else setting whatever to ["1"]:

 whatever = my_list[:] if my_list is not None else ['1']

But I have a feeling what you really want is maybe a single if my_list is None:

if my_list is None:
     my_list = ['1']
like image 44
Padraic Cunningham Avatar answered Dec 23 '22 04:12

Padraic Cunningham