Is there any way of checking through a list of objects to see if any of them have a specific value for an attribute (or attributes). Let's say you wanted a program to see if there were any cabinets in a list of cabinets that were 40 inches tall and 50 inches wide. Does python have a way of finding that?
1 Answer
You can use a list comprehension:
object_with_specific_attribute = [obj for obj in object_list if obj.length == 40 and obj.width == 50]
2 Comments
mgilson
OP's question doesn't necessarily request for a list of objects that satisfy the criteria -- You could probably get away with an
any(generator_expression) if short-circuiting is desired and only a boolean result is required.mgilson
And a very trivial nitpick: I would rename it
objects_with_specific_attribute (note, objects, not `object) to indicate that you have a sequence and not a scalar.