Python filter()
function constructs an iterator from elements of an iterable for which a function returns true. We can understand that filter
will test every element of iterators to be true or not.
A Quick Example
marks = [5, 7, 2, 8, 9]
def is_pass_test(x):
if m < 5:
return False
else:
return True
passes = filter(is_pass_test, marks)
print(list(passes))
# Result: [7, 8, 9]
Definition and Usage
The Python filter()
syntax is as follows:
filter(function, iterable)
- function: The function will be executed for each element of iterable.
- iterable: The iterable to be filtered.
Python Filter Examples
Example 1: Using lambda function with filter()
We can make above example a lot shorter by using lambda
with filter()
marks = [5, 7, 2, 8, 9]
passes = filter(lambda x: x > 5, marks)
print(list(passes))
# Result: [7, 8, 9]
You don't know what is lambda
, don't worry, read our article to understand it (What's lambda syntax in Python)
Example 2: Passing None function to filter()
datas = [5, False, '', True, 'Filtered', None]
passes = filter(None, datas)
print(list(passes))
# Result: [5, True, 'Filtered']
In this example, we passed None as a function parameter. However it is not a real None value, it means a default function. In this case, a default function equal to lambda x: x
References
As our goal to build a short and understandable tutorial. However, in case you would like to learn deeper, you should read below references:
- From Python Official Document
- From Python Tips Book
The post Python Filter Function appeared first on Python Geeks.
Top comments (0)