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
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.
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.
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() .
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.
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'))
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')]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With