ruk·si

# 🐍 Python - Comprehensions

Updated at 2018-06-09 14:55

Use list comprehensions `[value]`.

``````squares = [number * number for number in range(5)]
assert squares == [0, 1, 4, 9, 16]

even_squares = [number * number for number in range(5) if number % 2 == 0]
assert even_squares == [0, 4, 16]
``````

Use set comprehensions `{value}`.

``````squares = {number * number for number in range(5)}
assert squares == {0, 1, 4, 9, 16}
``````

Use dictionary comprehensions `{key: value}`.

``````squares = {number: number * number for number in range(5)}
assert squares == {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
``````

Use generator expressions `(value)`.

``````for x in ('Hello' for _ in range(3)):
assert x == 'Hello'
``````

Comprehensions and generator expressions can be nested. But avoid nesting comprehensions or expressions for more than 2 levels. Nesting can cause the code to become difficult to maintain.

``````colors = ['black', 'white']
sizes = ['S', 'M', 'L']
shirts = [(color, size) for color in colors
for size in sizes]
assert len(shirts) == 6
assert shirts == ('black', 'S')

jackets = ((color, size) for color in colors
for size in sizes)
for jacket in jackets:
assert isinstance(jacket, tuple)
``````
``````from typing import NamedTuple

class Product(NamedTuple):
name: str
price: int

products = [
Product(name='Apple', price=1),
Product(name='Ground Coffee', price=3),
]

total = sum((
product.price
for product
in products
), 0)
assert total == 6
``````

# Source

• Python Tricks The Book, Dan Bader
• Fluent Python, Luciano Ramalho