Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I don't remember whether I was dreaming or not but I seem to recall there being a function which allowed something like,

foo in iter_attr(array of python objects, attribute name)

I've looked over the docs but this kind of thing doesn't fall under any obvious listed headers

like image 721
Brendan Avatar asked Aug 03 '08 13:08

Brendan


People also ask

How do you find a specific object in a list Python?

To find an element in the list, use the Python list index() method, The index() is an inbuilt Python method that searches for an item in the list and returns its index. The index() method finds the given element in the list and returns its position.

Can you have an array of objects in Python?

Python arrays are a data structure like lists. They contain a number of objects that can be of different data types. In addition, Python arrays can be iterated and have a number of built-in functions to handle them. Python has a number of built-in data structures, such as arrays.

How do you find an object in Python?

Get and check the type of an object in Python: type(), isinstance() In Python, you can get, print, and check the type of an object (variable and literal) with the built-in functions type() and isinstance() .

Can you use arrays in Python?

Python has a set of built-in methods that you can use on lists/arrays. Note: Python does not have built-in support for Arrays, but Python Lists can be used instead.


2 Answers

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')) 
like image 141
Will Harris Avatar answered Sep 20 '22 13:09

Will Harris


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')] 
like image 45
Matt Avatar answered Sep 21 '22 13:09

Matt