I happened to find myself having a basic filtering need: I have a list and I have to filter it by an attribute of the items.
My code looked like this:
my_list = [x for x in my_list if x.attribute == value]
But then I thought, wouldn't it be better to write it like this?
my_list = filter(lambda x: x.attribute == value, my_list)
It's more readable, and if needed for performance the lambda could be taken out to gain something.
Question is: are there any caveats in using the second way? Any performance difference? Am I missing the Pythonic Way™ entirely and should do it in yet another way (such as using itemgetter instead of the lambda)?
An important difference is that list comprehension will return a
list
while the filter returns afilter
, which you cannot manipulate like alist
(ie: calllen
on it, which does not work with the return offilter
).My own self-learning brought me to some similar issue.
That being said, if there is a way to have the resulting
list
from afilter
, a bit like you would do in .NET when you dolst.Where(i => i.something()).ToList()
, I am curious to know it.EDIT: This is the case for Python 3, not 2 (see discussion in comments).
It took me some time to get familiarized with the
higher order functions
filter
andmap
. So i got used to them and i actually likedfilter
as it was explicit that it filters by keeping whatever is truthy and I've felt cool that I knew somefunctional programming
terms.Then I read this passage (Fluent Python Book):
And now I think, why bother with the concept of
filter
/map
if you can achieve it with already widely spread idioms like list comprehensions. Furthermoremaps
andfilters
are kind of functions. In this case I prefer usingAnonymous functions
lambdas.Finally, just for the sake of having it tested, I've timed both methods (
map
andlistComp
) and I didn't see any relevant speed difference that would justify making arguments about it.