Check if value in an array of objects


I recently wrote a code that had all attributes stored separately in different arrays like

order_id = []
order_name = []
order_products = []
order_total = []

And when importing new orders through an API request I would check if I already have that order by doing

if new_order_id in order_id:
    # do new order stuff

Now I want to change the code so that order is a class that has id, name, products and total as attributes and all orders are stored in an array called orders. Is there an easy way to check if the new order id matches the id of any order objects in the orders array?

Asked By: LukaJnk



One way to test for the existence of an object in a container is to give the object a "value" by way of the __eq__ magic method. For example:

class Order:
    def __init__(self, id):
        self.order_id = id
    def __eq__(self, other):
        return self.order_id == other

order_list = [Order('123'), Order('456')]

Then you can test for order numbers:

>>> '123' in order_list
>>> '345' in order_list
Answered By: sj95126
class oder():
    def __init__(self, id, name, products, total): = id = name
        self.products = products = total
oders=[]# Class objects are here

if in [ for oder in oders]:
    #Place an Order
Answered By: Aric a.
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.