Explore Courses Blog Tutorials Interview Questions
0 votes
in Python by (7.3k points)

I seem to recall there being a function which allowed something like this,

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

I have looked over the docs but this thing I can not find on any listed headers 

1 Answer

0 votes
by (106k points)

foo in iter_attr(array of python objects, attribute name) from your above function it seems like either you are trying to use list comprehension or Secure hashing algorithm.

List comprehension is used for creating a new list from other iterables. As a list comprehension returns list, they consist of brackets containing the expression, which is executed for each element using for loop.

If you are looking to get a list of objects that have certain attributes

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

But the best way to do this is Secure hashing algorithms. You can use it to your advantage because list comprehension iterates to every element which is a disadvantage of it.

Secure Hash Algorithm is a set of cryptographic hash functions defined by the language to be used for various applications such as password security and many more. Some variants of it are supported by Python in the “hashlib” library.

Objects hashed using hash() are irreversible, leading to loss of information.

hash() returns hashed value only for immutable objects, hence it can be used as an indicator to check for mutable/immutable objects.

Syntax : hash(obj)

obj : The object which we need to convert into hash.

Returns : Returns the hashed value if possible.

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

Browse Categories