Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python3 filter() Function

Python3 filter() Function

Python3 Built-in Functions Python3 built-in function


Description

filter() The function filters a sequence, removing elements that do not meet a condition, and returns an iterator object; use list() to convert it to a list.

It takes two arguments: the first is a function and the second a sequence. Each element of the sequence is passed to the function for a judgment that returns True or False, and the elements returning True are placed in a new list.

Syntax

The syntax of the filter() method is as follows:


filter(function, iterable)

Parameters

Return Value

Returns an iterator object


Example

The following shows examples of using the filter function:

Filter out all odd numbers in a 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:

[1, 3, 5, 7, 9]

Filter 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:

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Python3 Built-in Functions Python3 built-in function