Python filter()

The filter() function selects elements from an iterable based on the result of a function.

Example

# returns True if the argument passed is even
def check_even(number):
    if number % 2 == 0:
          return True  
    return False

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# if an element passed to check_even() returns True, select it even_numbers_iterator = filter(check_even, numbers)
# converting to list even_numbers = list(even_numbers_iterator) print(even_numbers) # Output: [2, 4, 6, 8, 10]

filter() Syntax

filter(function, iterable)

filter() Parameters

The function takes two parameters:

  • function - a function that runs for each item of an iterable
  • iterable - a sequence that needs to be filtered like sets, lists, tuples, etc

filter() Return Value

The filter() function returns an iterator.


Example: Filter Vowels From List

letters = ['a', 'b', 'd', 'e', 'i', 'j', 'o']

# a function that returns True if letter is vowel
def filter_vowels(letter):
    vowels = ['a', 'e', 'i', 'o', 'u']
    if letter in vowels:
        return True 
    else:
        return False

# selects only vowel elements filtered_vowels = filter(filter_vowels, letters)
# converting to tuple vowels = tuple(filtered_vowels) print(vowels) # Output: ('a', 'e', 'i', 'o')

Here's how the above program works:

  • each element of letters is passed to the filter_vowels() function
  • if filter_vowels() returns True, filter() selects the element

Note: Here, the program returns the iterator, which we converted into a tuple using the vowels = tuple(fitered_vowels).

More on Python filter()

Python filter() With Lambda

We can also use the Python filter() function with the lambda function. For example,

numbers = [1, 2, 3, 4, 5, 6, 7]

# the lambda function returns True for even numbers even_numbers_iterator = filter(lambda x: (x%2 == 0), numbers)
# converting to list even_numbers = list(even_numbers_iterator) print(even_numbers) # Output: [2, 4, 6]

In the above example, the lambda function returns True only for even numbers. Hence, the filter() function returns an iterator containing even numbers only.

Using None as a Function Inside filter()

When None is used as the first argument to the filter() function, it extracts all elements that evaluate to True when converted to boolean. For example,

random_list = [1, 'a', 0, False, True, '0']
filtered_iterator = filter(None, random_list)

# converting to list
filtered_list = list(filtered_iterator)

print(filtered_list)

# Output: [1, 'a', True, '0']

Here, 1, 'a' , True and '0' are considered True on conversion to booleans.

Also Read:

Video: Python map() and filter()

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges