Index ¦ Archives ¦ Atom

How to Filter a List in Python

li is some list, and I want to filter a list -- comparable to np.where(...) for a pure python list

In [1]:
li = ['a', 'b', 'c', 'a', 'b', 'a']
print(li)
['a', 'b', 'c', 'a', 'b', 'a']

using filter and lambda

In [8]:
t_m1 = %timeit -o list(filter(lambda x:x=='a', li))
1.38 µs ± 19.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
In [11]:
filtered_list = list(filter(lambda x:x=='a', li))
print(filtered_list)
['a', 'a', 'a']

using a list comprehension

In [12]:
t_m2 = %timeit -o [x for x in li if x == 'a']
595 ns ± 10.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
In [13]:
list_comp = [x for x in li if x == 'a']
print(list_comp)
['a', 'a', 'a']

comparing results of %timeit

In [15]:
t_m1.average
Out[15]:
1.3784109998565066e-06
In [16]:
t_m2.average
Out[16]:
5.946756401442273e-07
In [18]:
t_m1.average / t_m2.average
Out[18]:
2.3179207399889443

© Claus Haslauer. Built using Pelican. Theme by Giulio Fidente on github.