What is Python’s filter function and how to use it
Python’s filter()
function allows you to filter an iterable using a condition. Python then creates a new iterator that only includes the elements that meet the specified condition. This function can be applied to strings or used to remove null values.
What is Python filter()
?
The filter()
function in Python lets you apply a condition to an iterable and select the elements that satisfy the condition. What follows is an iterator that contains the filtered results. A condition is considered as being met if it is neither “0” or “false”. While there are other ways to filter lists and dictionaries in Python, the filter()
function is especially efficient. It creates an object that references the original iterable, using the function it’s provided and an index to filter the elements. This makes it much more memory-efficient when compared with other techniques for filtering.
What is the syntax for Python filter()
?
The syntax for Python filter()
is:
filter(function, iterable)
pythonAs you can see, Python filter()
has two parameters:
function
: This function is applied to each element within the iterable, returning a boolean value oftrue
orfalse
.iterable
: This parameter specifies what thefilter()
function should filter. A list, a set, another iterable or a python tuple can all be used as the argument for this parameter.
The filter function checks each element of the iterable against the condition that is provided in the first parameter. If the condition is true
, the element is included in the new sequence. If the element doesn’t meet the condition, it’s excluded.
Examples of Python filter()
In the following sections, we’ll demonstrate how the filter function works using clear examples that you can try at home.
Using filter()
with numbers
Let’s start by creating a series of numbers. Then, we’re going to create a condition that instructs the system to only consider values that are greater than 10. Using Python’s filter()
function, we’re going to filter the series of numbers. Here’s what the code looks like:
numbers = [3, 7, 9, 11, 17, 24, 25, 38, 40, 42]
def condition(x):
return x > 10
filtered_numbers = filter(condition, numbers)
filtered_numbers_list = list(filtered_numbers)
print(filtered_numbers_list)
pythonThe code above outputs the following list:
[11, 17, 24, 25, 38, 40, 42]
pythonUsing filter()
with strings
You can also use the filter()
function with strings in Python. In the following example, we’re going to instruct the system to filter a string for vowels. Here’s the code:
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
def is_vowel(letter):
vowels = ['a', 'e', 'i', 'o', 'u']
if letter in vowels:
return True
else:
return False
filtered_vowels = filter(is_vowel, letters)
filtered_vowels_tuple = tuple(filtered_vowels)
print(filtered_vowels_tuple)
pythonWe’ve changed the result into a tuple, so the output looks like this:
('a', 'e', 'i')
pythonCombining lambda
with filter()
in Python
You can also use the filter function with lambda functions in Python. A lambda function is an anonymous function that’s mainly used for local tasks. In the next example, we’re going to take a list of numbers and filter it so that there are only even numbers. Here’s how to write the code for this:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
new_iterator = filter(lambda x: (x % 2 == 0), numbers)
even_numbers = list(new_iterator)
print(even_numbers)
pythonThis gives us the following output:
[2, 4, 6, 8, 10]
pythonUsing the argument None
with filter()
Passing None
as the first argument to filter()
instructs the system to filter out falsy values. Falsy values are values that, according to Boolean logic, are not true or false but instead represent a null value. Essentially, they are considered empty.
In this example, we’re going to use a list that contains different values, including integers, empty values and Boolean values. Then, we’re going to apply Python’s filter()
and None
to remove the values that don’t meet the condition. Here’s the code:
values = [1, 2, 3, 'x', 0, 4, True, False, 5]
new_iterator = filter(None, values)
new_values = list(new_iterator)
print(new_values)
pythonHere’s the output:
[1, 2, 3, 'x', 4, True, 5]
pythonRemoving empty strings with None
If you want to remove empty strings, the easiest way to do so is using filter()
. Here’s one way to remove an empty string using Python’s filter function:
sentence = ['This', ' ', 'is', 'an', ' ', 'example', ' ']
sentence = list(filter(None, sentence))
print(sentence)
pythonEmpty strings will be filtered out, leaving only those strings that contain a value. Here’s what the output looks like:
['This', 'is', 'an', 'example']
pythonAutomatic framework detection, easy staging and an array of features—With Deploy Now from IONOS, you not only have access to reliable infrastructure, you also can deploy your website or app directly through GitHub. Find the plan that suits your development needs!