I have a list that I wanted to iterate over. When I used a list comprehension, it would fail if the list was None. But it would if the list was empty .
The old and easy way of doing this was:
if tags: for t in tags: # Do stuff with t
The pythonic way of merging the if statement within the list comprehension is:
for t in [t for t in (tags or )]: # Do stuff with t
If you had a dictionary, you could use a ternary condition within list comprehension:
([k for k, v in tags] if tags is not None else )
OR, You can embed the ternary condition in the comprehension as well:
[k for k, v in (tags if tags is not None else )]
The original stack overflow post.