Filtering retains only the items in an iterable that satisfy a condition. For example, selecting tasks with urgency greater than 3 produces a smaller collection containing only the relevant tasks. section 5.2.4
filtered_titles0 = []
for task in tasks:
if task.urgency > 3:
filtered_titles0.append(task.title)
assert filtered_titles0 == ['Homework', 'Museum']
The explicit approach checks each task and appends its title only when the urgency condition passes. section 5.2.4
filtered_titles1 = [task.title for task in tasks if task.urgency > 3] assert filtered_titles0 == filtered_titles1
A list comprehension expresses the same operation compactly: [expression for item in iterable if condition]. section 5.2.4
The filter function applies a predicate to every item, keeps items for which the predicate returns True, and excludes items for which it returns False. A lambda expression can provide the predicate. section 5.3.5
for task in filter(lambda x: x.urgency > 3, tasks): print(task)
This listing filters tasks with a lambda that tests urgency before printing each retained task. section 5.3.5
Choose the clearest form for the surrounding operation:
- Use a regular for loop when the condition or subsequent processing benefits from explicit, separate statements. section 5.3.6
- Use list, dictionary, or set comprehensions when filtering while creating the corresponding container. section 5.2.4 section 5.5
- Use filter when its function-based form reads naturally; it is a stylistic choice rather than a clearly superior replacement for an if statement. section 5.3.6
































