Actually, list comprehension is much clearer and faster than the filter+lambda combination, 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
Comment section code(François P.): Memory consumption and performance
The “filter” function returns a “filter” object which is an iterator intended to use in a for loop with little memory consumption.
So a generator comprehension is more similar to the “filter” function (than a list comprehension is).
I profiled the following code:
lst = list(range(int(1e7)))
def func1():
for even in (i for i in lst if i % 2 == 0):
pass
def func2():
for even in filter(lambda n: n % 2 == 0, lst):
pass
func1()
func2()
the generator comprehension (func1) is the fastest (830ms against 1.48s)
Do comment if you have any questions or doubts o this Python list topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Hi !
The “filter” function returns a “filter” object which is an iterator intended to use in a for loop with little memory consumption.
So a generator comprehension is more similar to the “filter” function (than a list comprehension is).
I profiled the following code:
“`python
lst = list(range(int(1e7)))
def func1():
for even in (i for i in lst if i % 2 == 0):
pass
def func2():
for even in filter(lambda n: n % 2 == 0, lst):
pass
func1()
func2()
“`
… and the generator comprehension (func1) is the fastest (830ms against 1.48s)
Cheers!
Added in the post, Thanks!