-->

how to use "filter" builtin function in python?

  • "filter" is a python's built-in function which can be found in module "__builtin__".
  • It takes two arguments, first argument as a function and second argument as sequence of objects/elements.
  • It passes all objects/elements to given function one after other.
  • If function returns "True" then it appends the object/element to a list & returns the list after passing all elements.
  • If sequence is a tuple or string, it returns the same type, else return a list. 
  • If function is None, return the items that are true.

Let's see an example for "filter"

Q. Find out the all prime numbers below hundred ?

 1. Traditional way

num = 100
primes = []
for i in range(2, 100):
for j in range(2, i):
if i % j == 0:
break
else:
primes.append(i)
print(primes)
# Output: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

2. Using function "filter"

def is_prime(num):
for j in range(2, num):
if num % j == 0:
return False
else:
return True
primes = filter(is_prime, range(1, 100))
print(primes)
# Output: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
print(type(primes))
# Output: list

Lets test filter by passing "None" as first argument

a = (0, 1, 2, 3)
l = filter(None, a)
print(l)
# Output: (1, 2, 3)
print(type(l))
# Output: tuple
It converts element to boolean if it returns true then it will add element to list/tuple/string.

Let's apply "filter" on strings.

Remove vowels from string in python.

def remove_vowels(char):
return char.lower() not in ['a', 'e', 'i', 'o', 'u']
s = filter(remove_vowels, "this is anjaneyulu batta")
print(s)
# Output: ths s njnyl btt

Buy a product to Support me