Comprehensions in Python

With step wise step illustrated examples

In python, comprehension is nothing but compressed form of loop and an expression in a single line.

Simple form

As you can notice in above picture, how a 4 lines of code can be compressed in a single line. A comprehensive has 3 parts

First the loop runs then the condition is checked which is of course optional. And finally expression is executed and appended to the list.

You can have multiple loops too. In this case, they will run in sequence from left to right as nested loops. Eg

2 loops comprehensive

Now if a condition is also present then just place it before the assignment. Eg

2 loops with condition

You can make the expression complex to handle if..else situation, or call some function to match a condition.

bin = [1,0,1,1,0,0,1,1,0]
[0 if a ==1 else 1 for a in bin] # [0, 1, 0, 0, 1, 1, 0, 0, 1]

Considering that you already know walrus operator. You can use it in comprehension as well to reduce number of repeated operations;

fruits = ["APPLE", "Banana", "berry", "melon"]
[f.lower() for f in fruits if f[0] == 'b' or f[0] == 'B' ]

Above expression can be re-written with walrus operator in following ways

fruits = ["APPLE", "Banana", "berry", "melon"]
[fLower for f in fruits if (fLower := f.lower())[0] == 'b' ]

Other Comprehensions

We can create the Set Comprehension in the same way. just change surrounding []to {}. Eg

bin = [1,0,1,1,0,0,1,1,0]
{0 if a ==1 else 1 for a in bin} # {0, 1}

Dictionary Comprehension has the same syntax but expression returns a both key value Eg

fruits = ["APPLE", "Banana", "berry", "melon"]
print({f: len(f) for f in fruits})

We can also create the Generator Comprehension same as for list or set. Just change surrounding []to (). Eg

bin = [1,0,1,1,0,0,1,1,0]
(0 if a ==1 else 1 for a in bin) #<generator object <genexpr> at ..>

List comprehension creates a list and append all the values of evaluated expression in this list. Whereas, in generator comprehension, a generator is returned which can be iterated further. So less memory is occupied. Hence, it is beneficial when we are dealing with long list. However, if that list can be re-used further then probably list comprehension can be useful.

When you don’t need comprehension?

Though comprehensions make the code a little faster, the main advantage is to concise the code and make it more understandable instead of making it verbose. So we should avoid comprehension with multiple loops or complex condition or expression. Or you can probably assign, particular part in different functions to make it more readable. Eg

[f.upper() for f in fruits if sweet(f)]

Similarly, we can directly use list()or set()instead of comprehension. Eg

bin = [1,0,1,1,0,0,1,1,0]
set(bin) # {0, 1}

Similarly, there are some functions which return iterator. They can be used in a for loop directly. So comprehension can be avoided in such cases.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store