1

This is my list

[<CorrectEntry: CorrectEntry object>, <CorrectEntry: CorrectEntry object>, <CorrectEntry: CorrectEntry object>]

CorrectEntry objects looks like this :

number 
message
etc

How would I check if a any of those objects in a list has a number that I am checking for?

So I want to check if the number ex. 123 is in any of the objects in the list?

1
  • Is you list a queryset? If yes, then it is better to use filter, or values_list` in your situation Commented Jul 5, 2013 at 10:51

1 Answer 1

8

Use the any() function with a generator expression:

if any(ce.number == yourvaluetotest for ce in correct_entries):
    # 

The function will loop over the generator expression until a true-ish value is returned, after which itself returns True. If no such value is found, False is returned instead. This is very efficient, as it will only test as many CorrectEntry values as needed to determine that there is one that matches.

Sign up to request clarification or add additional context in comments.

1 Comment

Works perfectly, great python

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.