Python list comprehension gotcha

List comprehensions in Python are handy.

You can even selectively disinclude certain list elements:

mylist = [element for element in otherlist if element.condition]

and you can replace those elements instead of disincluding them:

mylist = [element if element.condition else replacement for element in otherlist]

If you were paying attention you probably noticed that now we have to put the condition in front of the list comprehension syntax rather than behind it. That’s because we’re using a completely different operator now (the ternary operator in Python is necessary to replace the elements, whereas the list comprehension syntax is what allows us to not include some elements). Neither version can do the job of the other, though it seems like we should have just one way to do conditionals in list comprehensions.

Not very Pythonic, in my opinion.