Python Filter vs List Comprehension | Difference

Actually, list comprehension is much clearer and faster than filter+lambda, but you can use whichever you find easier. 

Here is the difference between filter vs list comprehension in coding

For the code that is easier to write and understand (or if you feel the filter() + lambda is confusing), you should choose the List comprehension. List comprehension is easier to read, understand, and type.

LIST COMPREHENSION

even = [i for i in range(20) if i % 2 == 0]

print(even)

FILTER + LAMBDA

even = filter(lambda n: n % 2 == 0, range(20))
print(list(even)) 

Python Lists filter() vs List Comprehension – Which is Faster?

Answer: When the list is so small there is no significant difference between the two. But if you want the code which is faster, I would tell you to choose the filter() + lambda. It is the faster one

Do comment if you have any questions or doubts o this Python list topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.