Need a list of values derived from an iterable? A list comprehension creates it in one expression: `[expression for item in iterable]`. The expression determines each value in the new list. This often reads more clearly than initializing a list and appending inside a loop. section 5.2.1
Extract and filter task titles
```python from collections import namedtuple Task = namedtuple('Task', 'title, description, urgency') tasks = [ Task('Homework', 'Physics and math', 5), Task('Laundry', 'Wash clothes', 3), Task('Museum', 'Egypt exhibit', 4), ] titles = [task.title for task in tasks] urgent_titles = [task.title for task in tasks if task.urgency > 3] assert titles == ['Homework', 'Laundry', 'Museum'] assert urgent_titles == ['Homework', 'Museum'] ``` The expression `task.title` selects what goes into the result; the trailing `if` selects which tasks contribute a value. section 5.2.1 section 5.2.4
Choose the form that matches the container you need:
- Use square brackets for a list. Add `if condition` after the iterable when only some items should contribute values. section 5.2 section 5.2.4
- Use a set comprehension to create a set of derived values; duplicate results are removed. Dictionary comprehensions likewise create dictionaries from iterables. section 5.2.3 section 5.2.6
- For nested data, put the outer `for` before the inner `for`, as you would with nested loops. Keep to at most two layers for readability. section 5.2.5
numbers = [-3, -2, -1, 0, 1, 2, 3]
squares = {x*x for x in numbers}
assert squares == {0, 9, 4, 1} #1
Squaring both negative and positive numbers produces repeated values; the set comprehension retains each result once. section 5.2.3
Use a constructor instead when the items need no transformation: `set(numbers)` is simpler than `{x for x in numbers}`. If the expression or nesting becomes hard to follow, use ordinary loops. A list comprehension is also usually less verbose than constructing a list with `map`; an iterator from `map` can still suit a loop that performs several operations. section 5.2.6 section 7.2.2





