I first encountered the term list comprehension by watching a talk on optimizing Python code by Sebastian Witowski.
I always knew this term existed but didn’t include it in my arsenal of tools while writing personal projects.
I mean, I don’t have to right?
So long as the code work and is maintainable, I’m good.
Now look at the following code:
output = []
for i in list:
if i % 2 == 0
output.append(i)
return output
Isn’t it clear and easy to understand?
There is no need for fancy one-liners.
We simply iterate through the list and only append it to the output if element i is an even number.
But as I start working on more projects, I realized that such a pattern occurs over and over again – to return a subset of the list that meets certain conditions.
It may not seem much if it’s just for a simple script or project.
However, as your script/project grows, all these extra lines of code will have an impact.
The above code can be simply replaced by:
return [i for i in list if i % 2 == 0]
To those who are unfamiliar with list comprehension. Here is the syntax:
[expression for i in list if condition]
It is equivalent to this:
for i in list:
if condition:
expression
List comprehension can also be useful for assertions.
For example, if we want to ensure that the list is in sorted order, we could simply use the:
assert all([list[i] <= list[i+1] for i in range(len(list)-1)])
all() is an in-built function that returns a True if every element in the list is True.
So our list comprehension starts iterating from 0 to the length of the list minus 1.
Our expression, list[i] <= list[i+1], will then check if the current value of list[i] is less than the next (note that list[i] will not reach the last element). And it will return the respective boolean value.
We can also use it to assert that every value in a dictionary is an integer.
assert all([type(value) is int for key, value in dictionary.items()])