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 = 12
foo 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 = 12
foo in (obj.id for obj in bar if hasattr(obj, 'id'))

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)