liveBook · Manning

Filtering

As explained in Python Workout, Second Edition

Filtering is a technique that selects elements satisfying a specified condition and excludes the others.

Filtering selects elements whose predicate result is truthy and excludes the rest without transforming the retained elements. In Python, filter applies a function to an iterable; list comprehensions can combine filtering with transformation. section 8.5 section 8.9

Use filtering when a coding task requires conditional inclusion:

  • Write a comprehension with an if clause to keep only integers between 0 and 10. section 8.5
  • Use filter with a named predicate such as is_a_long_word to retain words longer than four characters. section 8.5
  • Distinguish map, which transforms every input and preserves length, from filter, which controls inclusion without transforming elements. section 8.5

Practice variations

Filter text-file lines containing a vowel and more than 20 characters, or exclude person dictionaries representing people over 20 while adding age_in_months to retained records. section 8.9

words = 'this is a bunch of words'.split()     #1

def is_a_long_word(one_word):      #2
    return len(one_word) > 4

x = filter(is_a_long_word, words)      #3
print(' '.join(x))    #4

Shows a named predicate passed to filter and the retained words joined for output. section 8.5

How Python Workout, Second Edition covers it

How deep it goes
Explains predicate application and contrasts filtering with mapping, then extends the idea through multiple comprehension exercises.
Examples
Uses long-word selection, bounded integers, text-file lines, phone-number area codes, and age-enriched dictionaries.
What you can do after
Apply filtering with named predicates, filter, and list-comprehension conditions to solve selection exercises.
How it connects
Connects filtering with filter, map, list comprehensions, functions, predicates, and iterables.

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, Second Edition. The section links point to the parts of the book it draws on.