liveBook · Manning

Filtering

As explained in Tiny Python Projects: Learn coding and testing with puzzles and games

Filtering is the process of retaining items that satisfy specified selection criteria and removing the others.

Filtering retains elements whose test returns a truthy value and rejects the rest. Python’s filter() is a lazy higher-order function that consumes a function and an iterable. section 14.3.1

Use filtering to:

  • Keep consonants or cars whose names begin with “blue ”. section 14.3.1
  • Remove words outside minimum and maximum length limits. section 20.1.4
  • Retain characters belonging to string.ascii_letters. section 20.3.1

Filter words by length

list(filter(lambda word: 3 <= len(word) <= 6, ['', 'a', 'an', 'the', 'this'])) returns ['the', 'this']. Coerce the lazy result with list() when you need to inspect or print it. section 20.1.4

>>> shorter = ['', 'a', 'an', 'the', 'this']
>>> min_word_len = 3
>>> max_word_len = 6
>>> list(filter(lambda word: min_word_len <= len(word) <= max_word_len, shorter))
['the', 'this']

Shows a complete REPL example of filtering values with inclusive length bounds. section 20.1.4

How Tiny Python Projects: Learn coding and testing with puzzles and games covers it

How deep it goes
Explains predicates, truthiness, laziness, list() coercion, and equivalents using comprehensions, stopping short of implementation internals.
Examples
Demonstrates consonant extraction, blue-car selection, bounded word lengths, and ASCII-letter retention.
What it assumes
Assumes functions, iterables, list comprehensions, and Boolean truthiness, while clarifying filter() through small examples.
What you can do after
Apply it via Python’s filter() with predicates and iterables, then materialize results with list() when needed.
How it connects
Connects filtering with higher-order functions, lambda functions, iterables, map(), list comprehensions, and regular expressions.

Also explained in

Compare how 33 books explain filtering →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Tiny Python Projects: Learn coding and testing with puzzles and games. The section links point to the parts of the book it draws on.