Python Built-in Function filter:

The filter() is a built-in function in Python it is used to filter the elements from an iterable (list, tuple, etc.).

Signature

The signature for the filter() function is as shown below.

filter(function,iterable)

Parameters and return type

  • It takes two parameters. The first parameter is a function based on which the selection is made. At the same time, the second parameter will be iterable (list, tuple, etc.).
  • However, it returns an iterator.

Python Built-in Function filter Examples:

Example 1: We will take a list of numbers for this example. After that, we will write a function that returns true if a number is odd, otherwise false. We will then use this function as a parameter to filter the elements.

#Initializing
a = [2,3,4,5,6,7,8,9,10,13,16]
#Defining function
def odd(x):
    return x % 2 != 0

#Using Filter and printing 
r = filter(odd, a)
print('Original List :', a)
print('Filtered List :', list(r))

Output

Original List : [2, 3, 4, 5, 6, 7, 8, 9, 10, 13, 16]
Filtered List : [3, 5, 7, 9, 13]

Example 2: We will demonstrate a filter function with a string in this case. Here, we will remove some characters given in list l, from the string s.

#Initializing
s="python programming"
#Defining function
def rem(x):
    l=['p','y','t','h','o','n']
    if x in l:
        return False
    else:    
        return True

#Using Filter and printing 
r = filter(rem , s)
print('Original List :', s)
print('Filtered List :', list(r))

Output

Original List : python programming
Filtered List : [' ', 'r', 'g', 'r', 'a', 'm', 'm', 'i', 'g']

Example 3: For this example, let us take a function that filters numbers less than 100 and greater than 4000 from the list.

#Initializing
s=[12,445,342,22,4456,2241,335,16,5,443,2341,55,65,72,38,668,997,2536]
#Defining function
def num(x):
    if x >100 and x<4000:
        return True
    else:    
        return False

#Using Filter and printing 
r = filter(num , s)
print('Original List :', s)
print('Filtered List :', list(r))

Output

Original List : [12, 445, 342, 22, 4456, 2241, 335, 16, 5, 443, 2341, 55, 65, 72, 38, 668, 997, 2536]
Filtered List : [445, 342, 2241, 335, 443, 2341, 668, 997, 2536]

Conclusion

Hence, the filter() function returns an iterable with the values for which the function returns a true.

References

Happy Learning 🙂

Leave A Comment