Python filter: How to Filter Items in Python with Example

The filter() method filters the given iterable with the help of a function that tests each item in the iterable to be true or not. Python filter() method constructs the iterator from items of an iterable for which a function returns true.

Python filter()

Python filter() is an inbuilt function that returns an iterator where the items are filtered through a function to test if the item is accepted or not.

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).

Thanks for reading !!!

#python #python filter

Python filter: How to Filter Items in Python with Example
2.20 GEEK