liveBook · Manning

Filtering

As explained in Python Workout: 50 ten-minute exercises

Filtering is the technique of retaining elements that satisfy a condition while excluding others.

Filtering retains elements that satisfy a condition and excludes the rest. In Python, list comprehensions combine filtering with transformation, while filter applies a predicate without changing retained elements. section 7.5

Choose the form that matches the job:

  • Use a comprehension when you want to transform selected values, such as squaring only even numbers. section 7.5
  • Use filter when a function should decide which original elements remain, such as keeping words longer than four characters. section 7.5
  • Filtering can ignore invalid input before aggregation, such as excluding strings containing nondigits before summing integers. section 7.6

Filtering while converting input

Given `10 abc 20 de44 30 55fg 40`, retain only strings that can become integers, convert them, and sum the results to produce 100. section 7.6

[x*x                   #1
 for x in range(10)    #2
 if x%2 == 0]          #3

Read the comprehension in three parts: expression, iteration, and the condition that filters the output. section 7.5

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Explains comprehension conditions and filter predicates, contrasting selection with map transformation without pursuing implementation internals.
Examples
Demonstrates even-number selection, long-word retention, phone-number updates, age limits, and invalid numeric-string exclusion.
What it assumes
Assumes familiarity with Python functions, iterables, list comprehensions, and conditional expressions while clarifying map-filter differences.
What you can do after
Apply filtering through Python list comprehensions or filter, including selection before conversion and summation.
How it connects
Connects filtering with list comprehensions, map, iterables, predicates, transformation, and aggregation.

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 Workout: 50 ten-minute exercises. The section links point to the parts of the book it draws on.