Episode 23 of 29
Filters
Learn how to use the filter() function to select elements from sequences.
The filter() function selects elements that pass a test condition.
Basic Filter
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens) # [2, 4, 6, 8, 10]Filter with Named Functions
def is_adult(age):
return age >= 18
ages = [12, 18, 25, 8, 30, 16]
adults = list(filter(is_adult, ages))
print(adults) # [18, 25, 30]Combining Map and Filter
nums = range(1, 21)
result = list(map(lambda x: x ** 2, filter(lambda x: x % 2 == 0, nums)))
print(result) # Squares of even numbers