[PYTHON] filter vs comprehension

Which is faster, filter or comprehension?

Which is faster, if you condition it with comprehension notation or if you pass the condition to filter with lambda?

iter = 10000

#Comprehension notation
for _ in tqdm(range(iter)):
    [i for i in range(iter) if i % 2 == 0]

#filter only
for _ in tqdm(range(iter)):
    filter(lambda i: i % 2 == 0, range(iter))

#Cast to list from filter
for _ in tqdm(range(iter)):
    list(filter(lambda i: i % 2 == 0, range(iter)))

I compared each one.

conditions iter/s
Comprehension notation 1531.51
filteronly 1169176.56
filterfromlistCast to 880.30

~~ filter was the overwhelming victory. ~~ ~~ However, if you have to make it list in the subsequent processing, it seems that the inclusion notation will be better. ~~

And, it is natural that filter wins overwhelmingly in comparison as above. https://qiita.com/licht-e-jima/items/0ef1e630c9afb771c040#comment-0882f662a1eb61d3e602 That's right. Thank you for your advice.

Recommended Posts

filter vs comprehension
Python comprehension
List comprehension
Comprehension notation
Python comprehension
Set comprehension
List comprehension
Comprehension notation