Python

What are python comprehensions?

Python comprehensions are an awesome mechanism that allows you to generate a list, dict, or set from another

What are comprehensions?

Comprehensions are a concise way of generating one list/dict/set from another list/dict/set. For example, let’s say that you have a list of prices of products in a list but you would like to know the total of each product with tax added on.

List comprehension example

prices = [3.99, 4.99, 1.09, 76.59, 10.99, .95]
tax_rate = 1.06
prices_with_tax = [ price * tax_rate for price in prices ]
for price in prices_with_tax:
    print(f'{price:.2f}')

Output:

4.23
5.29
1.16
81.19
11.65
1.01

The above will iterate through the input list (prices) multiply each by our taxation rate, 106% in this case, and save the result into a new list called “priceswithtax”.

What are comprehensions made up of?

Comprehensions have three parts:

Comprehensions can also do conditions

Let’s say you are interested only in returning prices for products whose original price is less than 11.

prices_under_11 = [ price * tax_rate for price in prices if price < 11 ]
for price in prices_under_11:
    print(f'{price:.2f}')

Output:

4.23
5.29
1.16
11.65
1.01

Dictionary Comprehension

Set comprehensions

There are no Tuple comprehensions

Drawbacks and things to keep in mind

Memory considerations - use generators? Map or comprehension? Item 8: avoid more than two expressions in list comprehensions (Bret Slatkin) Item 9: consider generator expressions (Bret Slatkin)