Python3 filter() Function
Description
filter()The function is used to filter sequences, filtering out elements that do not meet the conditions, and returns an iterator object. If you want to convert it to a list, you can uselist()to convert.
It accepts two parameters: the first is a function, the second is a sequence. Each element of the sequence is passed to the function as a parameter for judgment, which then returns True or False. Finally, the elements that return True are placed into a new list.
Syntax
The following is the syntax of the filter() method:
filter(function, iterable)
Parameters
- function -- judgment function.
- iterable -- iterable object.
Return Value
Returns an iterator object
Example
The following shows an example of using the filter function:
Filter out all odd numbers in the list:
#!/usr/bin/python3
def is_odd(n):
return n % 2 == 1
tmplist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
newlist = list(tmplist)
print(newlist)
Output result:
[1, 3, 5, 7, 9]
Filter out numbers from 1 to 100 whose square root is an integer:
#!/usr/bin/python3
import math
def is_sqr(x):
return math.sqrt(x) % 1 == 0
tmplist = filter(is_sqr, range(1, 101))
newlist = list(tmplist)
print(newlist)
Output result:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]Other Extensions
Python3 Built-in Functions