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.
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']
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With