List comprehensions are powerful technique for creating list and dictionaries in python. The common use cases are iterate over a collection, perform something with each element and finally collect the result into a list, dict or tuple.

List comprehension introduction for beginners

The basic syntax for list comprehension is:

double = [x*2 for x in range(5)]
print(double)

which result in:

[0, 2, 4, 6, 8]

The equivalent code of this with lambda expression is:

double = list(map(lambda x: x*2, range(5)))

while the normal loop equivalent is in 3 lines of code:

squares = []
for x in range(5):
    squares.append(x*2)

For readability and better code I prefer to use code comprehension where it's possible. Another benefit of using list comprehension is the easiness to be learn and used for beginners. You can create a list or dictionary depending on your data.

You can filter elements by using list comprehensions and if. The example below shows how to filter odd elements in our first example:

double = [x*2 for x in range(5) if x % 2 != 0]
print(double)

the result of this operation is:

[2, 6]

You can also use nested list comprehensions by:

sum = [x+y for x in range(3) for y in range(3)]
print(sum)

result:

[0, 1, 2, 1, 2, 3, 2, 3, 4]

You can even combine nesting and filtering in one example:

filt_nest = [(x, y) for x in [3,2,1] for y in range(3) if x == y]
print(filt_nest)

output:

[(2, 2), (1, 1)]

Practical examples for list comprehension

Now we will demonstrate advanced techniques for iterating a dictionary and creating a dictionary by using list comprehension. First example iterates over a list but finally create a dictionary:

List to dict with comprehension

countries_list = ['Brazil', 'Italy', 'Egypt', 'Canada', 'China', 'Panama', 'Mexico']
d = {key.lower(): key for key in countries_list}
print(d)

resulted dict is:

{'brazil': 'Brazil', 'italy': 'Italy', 'egypt': 'Egypt', 'canada': 'Canada', 'china': 'China', 'panama': 'Panama', 'mexico': 'Mexico'}

Dict to dict with comprehension

In next example we iterate over a dictionary to create another dictionary in which keys and values are exchanged:

countries_dict = {'Brasilia': 'Brazil', 'Rome': 'Italy', 'Cairo': 'Egypt', 'Ottawa': 'Canada', 'Beijing': 'China', 'Panama City': 'Panama', 'Mexico City': 'Mexico'}
dict_rev = {v: k for k, v in countries_dict.items()}
print(dict_rev)

result:

{'Brazil': 'Brasilia', 'Italy': 'Rome', 'Egypt': 'Cairo', 'Canada': 'Ottawa', 'China': 'Beijing', 'Panama': 'Panama City', 'Mexico': 'Mexico City'}

Return two lists with list comprehension

You can also return more than list by using list comprehensions. The example below shows how to return two lists at the same time: one with squares and one with doubles:

double, square = zip(*[(i*2, i**2) for i in range(5)])
print(double)
print(square)

result:

(0, 2, 4, 6, 8)
(0, 1, 4, 9, 16)

Note: some users doesn't know the python terminology and they use: Python for-in loop preceded by a variable instead of list comprehensions.

This covers 99% of the use cases that I've ever met related to list comprehensions. If you have a problem or any idea please do share it in the comment section below.