..

Comprehensions in python

Comprehensions in python are a great tool to simplify iterating and creating lists. They can increase readability when used right. But, be on the lookout for when they might reduce readability. Tip: Readability > Shortcuts

The key to comprehensions is the syntax. Practice to become familiar with it.

Table of contents

List

Using a for loop to double value of each number in the list:

my_list = [2, 4, 8]
new_list = []

for number in my_list:
    new_list.append(number * 2)

print(new_list)

Output:

[4, 8, 16]

Using list comprehension:

my_list = [2, 4, 8]
new_list = [ number * 2 for number in my_list ]
print(new_list)

Breaking down the syntax:

[ number * 2 for number in my_list ]

We enclose within ‘[]’ to return a list

[ number * 2 for number in my_list ]

The first part is the expression. In a regular for loop expression comes afterwards. In list comprehension it comes first. This is the key to remembering the syntax.

[ number * 2 for number in my_list ]

The rest of the syntax looks very much like regular for loop: for item in list

Set

Set comprehension follows same principal as lists. This will return a set (notice the curly braces):

my_list = [2, 4, 8]
new_list = { number * 2 for number in my_list }
print(new_list)

Output:

{4, 8, 16}

Dictionary

This will return a dict (notice the curly braces and key:value being returned)

my_dict = [2, 4, 8]
new_list = { number:number * 2 for number in my_dict }
print(my_dict)

Output:

{2: 4, 4: 8, 8: 16}

Additional tips