liveBook · Manning

Filtering

As explained in Python How-To

Filtering is the technique of retaining only the items in a collection that satisfy a specified condition.

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

How Python How-To covers it

How deep it goes
Defines condition-based retention, demonstrates loops, comprehensions, and filter, and defers detailed lambda treatment.
Examples
Uses task records with urgency above 3, retaining the Homework and Museum tasks through loops, comprehensions, and filter.
What it assumes
Assumes iterable and for-loop familiarity while treating lambda functions only as an introductory expression-based function.
What you can do after
Apply it via for loops, comprehensions, or filter to select items from iterables.
How it connects
Ties filtering to for loops, list comprehensions, dictionary comprehensions, set comprehensions, lambda functions, and iteration tools.

Also explained in

Compare how 33 books explain filtering →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.