Using 'in' to match an attribute of Python objects in an array Using 'in' to match an attribute of Python objects in an array arrays arrays

Using 'in' to match an attribute of Python objects in an array


Using a list comprehension would build a temporary list, which could eat all your memory if the sequence being searched is large. Even if the sequence is not large, building the list means iterating over the whole of the sequence before in could start its search.

The temporary list can be avoiding by using a generator expression:

foo = 12foo in (obj.id for obj in bar)

Now, as long as obj.id == 12 near the start of bar, the search will be fast, even if bar is infinitely long.

As @Matt suggested, it's a good idea to use hasattr if any of the objects in bar can be missing an id attribute:

foo = 12foo in (obj.id for obj in bar if hasattr(obj, 'id'))


Are you looking to get a list of objects that have a certain attribute? If so, a list comprehension is the right way to do this.

result = [obj for obj in listOfObjs if hasattr(obj, 'attributeName')]


you could always write one yourself:

def iterattr(iterator, attributename):    for obj in iterator:        yield getattr(obj, attributename)

will work with anything that iterates, be it a tuple, list, or whatever.

I love python, it makes stuff like this very simple and no more of a hassle than neccessary, and in use stuff like this is hugely elegant.