filter()
Introduction
# -> returns only those elements of iterable # where function returned True
Syntax
filter(function, sequence)
Example
The simplest example
# filter() positives = filter(lambda x: x > 0, [1, -5, 0, 6, -2, 8]) print(positives) print(list(positives)) # Filtering with None trues = filter(None, [0, 1, False, True, [], [1, 2, 3], '', 'hello']) print(list(trues)) # In Python2 map() and filter() are not lazy as in Python3. # They are eager and return lists
<filter object at 0x7f5e0bf2e2b0> [1, 6, 8] [1, True, [1, 2, 3], 'hello']
Using together with split()
split()
may produce not quite the result that you want. In particular it adds empty strings, which you can get rid of with the help of filter() because an empty string returns False.
Suppose you need to get from /hei/hei/ a
list
of hei and hei
>>> '/hei/hei/'.split('/') ['', 'hei', 'hei', ''] >>> list(filter(None, '/hei/hei/'.split('/'))) ['hei', 'hei']
Article author: Andrei Olegovich