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
































