Python filter() Function

The filter() function in Python is used when we need to modify an iterator. This function takes two parameters, the first parameter refers to the function that performs the modification, whereas the second parameter refers to an iterator object to modify. For example:

nums = [12, 23, 34, 45, 56, 67, 78, 89, 90]

def myfun(x):
    if x%2 == 0:
        return True
    else:
        return False

even = filter(myfun, nums)

for val in even:
    print(val)

The output produced by this program would be:

12
34
56
78
90

Python filter() Function Syntax

The syntax of filter() function in Python is:

filter(function, iterable)

where function refers to a user-defined function that will get created to check for each item available in the iterable such as list, tuple etc.

Python filter() Function Example

Here is an example of filter() function in Python. This program allows user to enter a string at run-time of the program. Using the list() function, all the characters of string gets initialized to char list. And using the filter() function, it gets filtered in a way to print the same string without vowel:

print("Enter the String: ", end="")
str = input()

chars = list(str)
vowels = ['A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u']

def myfun(x):
    if x not in vowels:
        return True
    else:
        return False

v = filter(myfun, chars)
print("\nThe string without vowel = ", end="")
for c in v:
    print(c, end="")

The snapshot given below shows the sample run of this program, with user input codescracker dot com:

python filter function

Python Online Test


« Previous Function Next Function »



Like/Share Us on Facebook 😋