(Sponsors) Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!
Python filter() function
Updated on Jan 07, 2020
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:
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:
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:
Other Tutorials (Sponsors)
This site generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!
View Comments