Python Func Filter
# Python2.x Python filter() Function
[ Python Built-in Functions](#)
* * *
## Description
The **filter()** function is used to filter a sequence, removing elements that do not meet the conditions, and returns a new list composed of elements that meet the conditions.
It takes two arguments: the first is a function, and the second is a sequence. Each element of the sequence is passed as an argument to the function for evaluation, which then returns True or False. Finally, the elements that returned True are placed into a new list.
> **Note:** Python2.7 returns a list, while Python3.x returns an iterator object. For more details, see: [Python3 filter() Function](#)
### Syntax
The syntax for the filter() method is:
filter(function, iterable)
### Parameters
* function -- The judgment function.
* iterable -- An iterable object.
### Return Value
Returns a list.
* * *
## Examples
The following examples demonstrate the use of the filter function:
## Filter out all odd numbers from a list:
#!/usr/bin/python# -*- coding: UTF-8 -*-def is_odd(n): return n % 2 == 1 newlist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])print(newlist)
Output:
[1, 3, 5, 7, 9]
## Filter out numbers between 1 and 100 whose square root is an integer:
#!/usr/bin/python# -*- coding: UTF-8 -*-import math def is_sqr(x): return math.sqrt(x) % 1 == 0 newlist = filter(is_sqr, range(1, 101))print(newlist)
Output:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
[ Python Built-in Functions](#)
YouTip