I have a list of custom Python objects and need to search for the existence of specific objects within that list. My concern is the performance implications of searching large lists, especially frequently.
Here's a simplified example using a custom Person class with attributes name and age:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
people = [Person("Alice", 30), Person("Bob", 25), Person("Charlie", 35)]
Currently, I'm using a list comprehension and the any() function to check if a person with a specific name and age exists in the list:
if any(p.name == "Bob" and p.age == 25 for p in people):
print("The person exists.")
Is there a more efficient way to search for the existence of specific custom objects within large Python lists?
I mean technically speaking if equality checks are set up for it, you could create the
Personobject you're looking for and just see if it's in the list.This will only work if the
Personobject you use in your condition and thePersonobject in the list evaluate to the same object. So this solution may or may not work for you.You could also stand to gain performance by using a set inistead of a list as stated in @RandomGuy's comment.
Edit:
If you want a more appropriate search you can use a set or a dict: