0

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

1 Answer 1

2

You can use a list comprehension:

object_with_specific_attribute = [obj for obj in object_list if obj.length == 40 and obj.width == 50]
Sign up to request clarification or add additional context in comments.

2 Comments

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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.