lets assume the following simple Object:
class Mock:
def __init__(self, name, age):
self.name = name
self.age = age
then I
List comprehensions are almost always the faster way to do these things (2x as fast here), though as mentioned earlier indexing is even faster if you're concerned about speed.
~$ python -mtimeit -s"from mock import myList" "filter(lambda x: x.age==21, myList)"
1000000 loops, best of 3: 1.34 usec per loop
~$ python -mtimeit -s"from mock import myList" "[x for x in myList if x.age==21]"
1000000 loops, best of 3: 0.63 usec per loop
For file mock.py
in current directory:
class Mock:
def __init__(self, name, age):
self.name = name
self.age = age
myList = [Mock('Tom', 20), Mock('Dick', 21), Mock('Harry', 21), Mock('John', 22)]