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.

Before you keep reading...

Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.

2. Using filter, filter lst so that it only contains words containing the letter “o”. Assign to variable lst2. Do not hardcode this.

You have attempted 1 of 5 activities on this page