Python’s filter() Function

Last Updated On Friday 10th Jun 2022

filter in python

The filter() is a built-in function that allows you to process an iterable (list, tuple etc.) for which a function returns True.

Syntax

	filter(function, iterable)
	

Note: Since filter() is a built-in function, you don’t have to import anything to be able to use it in your code.

Arguments

  • function – The first argument to filter() is a function object, which means that you need to pass a function without calling it with a pair of parentheses.
  • iterable – The second argument, iterable, can hold any Python iterable, such as a list, tuple, or set.

Return Value

Note: You can easily convert iterators to sequences like lists, tuples, strings etc.

filter python

Example 1

Filter out the number less than 20 in given list.

	numberList = [11, 22, 33, 14, 15, 16, 20, 4, 5, 1, 43, 55, 66]

def getLessThan20Func(numList):
    if(numList < 20):
        return True
    else:
        return False

numbers = filter(getLessThan20Func, numberList)

for i in numbers:
    print(i)
	

Output

	11
14
15
16
4
5
1
	

Example 2

Lets filter the vowels in given list

	letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',  'o']

def filterVowels(letter):
    vowels = ['a', 'e', 'i', 'o', 'u']
    return True if letter in vowels else False

filtered = filter(filterVowels, letters)

vowels = tuple(filtered)
print(vowels)
	

Output

	('a', 'e', 'i', 'o')
	

Example 3

Let’s filter the even numbers from the given list of numbers using the filter function

	numberList = [11, 22, 33, 14, 15, 16, 20, 4, 5, 1, 43, 55, 66]

def isEven(numList):
    if(numList %2 == 0):
        return True
    else:
        return False

numbers = filter(isEven, numberList)

for i in numbers:
    print(i)
	

Output

	22
14
16
20
4
66
	
filter function in python
filter list python
list filter python
filter function python
filter python function
python filter
python filter function
python filter list