List filtering: list comprehension vs. lambda + filter
- by Agos
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:
list = [i for i in list if i.attribute == value]
But then i thought, wouldn't it be better to write it like this?
filter(lambda x: x.attribute == value, 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)?
Thanks in advance