Harry
Harry

Reputation: 13329

Check if string in list of objects

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?

Upvotes: 1

Views: 223

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121942

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.

Upvotes: 8

Related Questions