This is an archived version of the course and is no longer updated. Please find the latest version of the course on the main webpage.

filter()

The second built-in higher-order function that we will look at is filter().

filter(func, iterable) returns only elements in iterable when func returns True for the element.

Basically, it filters iterable according to func.

For example, you might want to filter a list. Guess what the following program does? (See the importance of using meaningful names?)

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
even_numbers = list(filter(lambda x:x%2==0, numbers))
print(even_numbers)

The list comprehension equivalent is:

even_numbers = [n for n in numbers if x%2==0]

Another example:

phrases = ["Hello MSc AI!", "Dear computer scientists", "Welcome AI4Health CDT"]
ai_phrases = list(filter(lambda x: "AI" in x, phrases))
print(ai_phrases)

And the list comprehension equivalent is:

ai_phrases = [phrase for phrase in phrases if "AI" in x]

Exercises

Task 1

Given a list of words, use filter() and lambda functions to remove all words that are shorter than 5 characters.

words = ["Oh", "I", "wanna", "dance", "with", "somebody"]

## Expected output
## ['wanna', 'dance', 'somebody']

Task 2

Given x = range(10, 1000), use filter() and lambda functions to filter x to keep only numbers that are palindromes. (Remember that a palindrome is a word that reads the same forwards and backwards, e.g. 101, 262)

Task 3

Given the list below, use map(), filter() and lambda functions to return a list with values < 5000, and add 100 to all these values.

numbers = [2534, 423, 8000, 1000, 12345, 12, 54321]

# Expected output
# [2634, 523, 1100, 112]