The filter
function helps create filtered views of data. By the end of this lesson, you'll know how to use the filter
function effectively, both with lambda functions and predefined functions.
The filter
function is built into Python to create an iterator from elements of an iterable that satisfy a function. It’s useful for extracting specific elements from a list, tuple, or any iterable based on a condition.
Here’s the basic syntax:
Python1filter(function, iterable)
function
: A function that tests elements in theiterable
.iterable
: Any iterable (e.g., list, tuple).
Let's see a basic example. Suppose you have a list of numbers and want to keep only the even numbers:
Python1def is_even(x): 2 return x % 2 == 0 3 4if __name__ == "__main__": 5 # List of numbers 6 numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 7 8 # Filter even numbers 9 evens = list(filter(is_even, numbers)) 10 print("Even numbers:", evens) # Even numbers: [2, 4, 6, 8, 10]
The is_even
function checks if a number is even. The filter
function keeps only elements for which is_even
returns True
.
As before, we can utilize lambdas to make the code more clean. Here’s how to use a lambda function to filter even numbers:
Python1if __name__ == "__main__": 2 # List of numbers 3 numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 4 5 # Filter even numbers using lambda 6 evens = list(filter(lambda x: x % 2 == 0, numbers)) 7 print("Even numbers:", evens) # Even numbers: [2, 4, 6, 8, 10]
The lambda function lambda x: x % 2 == 0
does the same job as is_even
, but more concisely.
Predefined functions are helpful when you have a complex condition. Let’s filter out prime numbers from a list. First, define a function to check if a number is prime:
Python1def is_prime(x): 2 if x < 2: 3 return False 4 for i in range(2, int(x ** 0.5) + 1): 5 if x % i == 0: 6 return False 7 return True
Now, use the is_prime
function with filter
:
Python1def is_prime(x): 2 if x < 2: 3 return False 4 for i in range(2, int(x ** 0.5) + 1): 5 if x % i == 0: 6 return False 7 return True 8 9if __name__ == "__main__": 10 # List of numbers 11 numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 12 13 # Filter prime numbers 14 primes = list(filter(is_prime, numbers)) 15 print("Prime numbers:", primes) # Prime numbers: [2, 3, 5, 7]
The is_prime
function checks if a number is prime. The filter
function uses it to keep only prime numbers from numbers
.
We covered:
- The
filter
function’s purpose and usage. - Using
filter
with lambda functions for simple filters. - Using
filter
with predefined functions for complex conditions.
Now, move to the practice section to apply your knowledge. You will filter different datasets using lambda and predefined functions to solidify your understanding of the filter
function in Python.