Python List comprehension tutorial

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: