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
































