-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathfilter_list.py
More file actions
34 lines (23 loc) · 778 Bytes
/
filter_list.py
File metadata and controls
34 lines (23 loc) · 778 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# filter_list.py
"""
Filter a list
python -m timeit -s "from filter_list import test_loop" "test_loop()"
33.5 msec
python -m timeit -s "from filter_list import test_filter" "test_filter()"
49.9 msec
python -m timeit -s "from filter_list import test_comprehension" "test_comprehension()"
25.9 msec
"""
NUMBERS = range(1_000_000)
def test_loop():
odd = []
for number in NUMBERS:
if number % 2:
odd.append(number)
return odd
# It's slower because the list creation takes time
# But if you don't need to create a list and can use the iterator returned from filter(), it's a good solution
def test_filter():
return list(filter(lambda x: x % 2, NUMBERS))
def test_comprehension():
return [number for number in NUMBERS if number % 2]