Comprehensions
A comprehension builds a list, dict or set from an iterable in one expression: [expr for item in iterable if condition]. It replaces the four-line "create empty, loop, test, append" pattern and is usually faster. The rule for readability: one for, at most one if, and if it does not fit on one line, write the loop.
You should see
True [9, 16, 25, 4]
{'apple': 5, 'fig': 3, 'banana': 6}
{3, 5, 6}
['even', 'odd', 'even', 'odd']
[1, 2, 3, 4, 5]
333332833333500000orders = [{"id": 1, "total": 30}, {"id": 2, "total": 5}, {"id": 3, "total": 12}], make a dict of id → total for orders over 10, in one comprehension.Too clever
[f(x) for x in xs if g(x) for y in h(x) if y]- A comprehension only for its side effect:
[print(x) for x in xs] - Three levels of nesting
Just right
[x.strip() for x in lines if x]- A loop, when there is a side effect
- Two comprehensions with a named intermediate
