Python filter() function
Published February 16, 2022The filter() function is a built-in Python function that allows iterables to be processed and items that satisfy a specified condition to be extracted from the program. You may use the filter() method to apply the filtering process to build a new iterable containing the items that fulfil the undeliverable condition. This is referred to as filtering.
The syntax
You can give a function that returns true or false depending on a condition.
The filter() function has the following syntax:
filter(function, iterable), |
where the first argument takes a single parameter and returns a Boolean result. This function is critical to the decision function. The second parameter, iterable, could be any Python iterable, such as a set, tuple, generator, or list.
Example
def fun(var): x = ['p', 'y', 't', 'h', 'o','n'] if (var in x): return True else: return False a = ['p', 'y', 'y', 'o', 'n', 'h', 'p', 'y'] filtered = filter(fun, a) print('The filtered letters are:') for s in filtered: print(s) |
output:
The filtered letters are: p y y o n h p y |
Article Contributed By :
|
|
|
|
235 Views |