23.3. Filter¶
Now consider another common pattern: going through a list and keeping only those items that meet certain criteria. This is called a filter.
Again, this pattern of computation is so common that Python offers a more compact and general way to do it, the filter
function. filter
takes two arguments, a function and a sequence. The function takes one item and return True if the
item should. It is automatically called for each item in the sequence. You don’t have to initialize an accumulator or
iterate with a for loop.
Check Your Understanding
1. Write code to assign to the variable filter_testing
all the elements in lst_check that have a “w” in them using filter.
2. Using filter, filter lst
so that it only contains words containing the letter “o”. Assign to variable lst2
. Do not hardcode this.