Python filter() function

Updated on Nov 08, 2019


The filter() function takes a function and a sequence as arguments and returns an iterable, only yielding the items in sequence for which function returns True. If None is passed instead of a function, all the items of the sequence which evaluates to False are removed. The syntax of the filter() is as follows:

Syntax: filter(function or None, iterable) --> filter object

Here is an example:

Python 3

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
>>> 
>>> def is_even(x):
...     if x % 2 == 0:
...         return True
...     else:
...         return False
... 
>>> 
>>> f = filter(is_even, [1, 3, 10, 45, 6, 50])
>>>
>>> f
<filter object at 0x7fcd88d54eb8>
>>> 
>>> 
>>> for i in f:
...     print(i)
... 
10
6
50
>>>

Try it out:

def is_even(x):
    if x % 2 == 0:
        return True
    else:
        return False

f = filter(is_even, [1, 3, 10, 45, 6, 50])

print(f)

for i in f:
    print(i)

To produce the result at once we can use the list() function.

Python 3

1
2
3
4
5
6
7
8
>>> 
>>> list(filter(is_even, [1, 3, 10, 45, 6, 50]))
[10, 6, 50]
>>>
>>> 
>>> list(filter(None, [1, 45, "", 6, 50, 0, {}, False])) # function argument is None
[1, 45, 6, 50]
>>>

Try it out:

def is_even(x):
    if x % 2 == 0:
        return True
    else:
        return False

print( list(filter(is_even, [1, 3, 10, 45, 6, 50])) )

# function argument is None
print( list(filter(None, [1, 45, "", 6, 50, 0, {}, False])) ) 

In Python 2, filter() returns an actual list (which is not the efficient way to handle large data), so you don't need to wrap filter() in a list() call.

Python 2

1
2
3
4
>>> 
>>> filter(is_even, [1, 3, 10, 45, 6, 50])
[10, 6, 50]
>>>

Here are some other examples.

Python 3

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
>>> 
>>> filter(lambda x: x % 2 != 0, [1, 3, 10, 45, 6, 50]) # lambda is used in place of a function
[1, 3, 45]
>>>
>>> 
>>> list(filter(bool, [10, "", "py"]))
[10, 'py']
>>> 
>>>
>>> import os
>>> 
>>> # display all files in the current directory (except the hidden ones)
>>> list(filter(lambda x: x.startswith(".") != True, os.listdir(".") )) 
['Documents', 'Downloads', 'Desktop', 'Pictures', 'bin', 'opt', 'Templates', 'Public', 'Videos', 'Music']
>>>

Try it out:


# lambda is used in place of a function
print(filter(lambda x: x % 2 != 0, [1, 3, 10, 45, 6, 50])) 
 
print(list(filter(bool, [10, "", "py"])))

import os
 
# display all files in the current directory (except the hidden ones)
print(list(filter(lambda x: x.startswith(".") != True, os.listdir(".") )) )

Other Tutorials (Sponsors)