In our last snippet post we introduced list comprehensions, but there's a lot more still to cover. We can also include conditional clauses in our list comprehensions to filter out items we don't want to include in our new list.
Including a conditional clause in a list comprehension is quite simple. We just have to use the if key word after the loop definition:
names = ["Matthew", "John", "Helen", "Stephen", "Alexandra", "Rolf"] short_names = [name for name in names if len(name) < 6] # ['John', 'Helen', 'Rolf']
Here we filter out all names longer than 5 characters.
One common mistake people make is putting a condition at the beginning of the list comprehension. This is legal syntax but means something else entirely.
names = ["Matthew", "John", "Helen", "Stephen", "Alexandra", "Rolf"] short_names = [len(name) < 6 for name in names] # [False, True, True, False, False, True]
Here the list comprehension adds a Boolean value to the new list for each
names. This can be very useful in the right circumstances, but it's often not what you want.
Like with for clauses, list comprehensions allow for numerous if clauses in sequence:
names = ["Matthew", "John", "Helen", "Stephen", "Alexandra", "Rolf"] short_final_n = [name for name in names if len(name) < 6 if name[-1] == "n"] # ['John', 'Helen']
Here names only make it into our new list if they are both less than 6 characters long and end with
n. I'm not a big fan of chaining together conditions like this in a comprehension, but there are definitely cases where it will be perfectly readable and easy to follow.
If you're interested in learning more about list comprehensions, be sure to check out the official documentation.