Search code examples
pythonclassattributesany

Check if class property value exists in list of objects


I have a class with 2 properties:

class ButtonPress():
    def __init__(self, time, button):
        self.time = time
        self.button = button

I create a list with ButtonPress objects inside them:

buttonlist = []
buttonlist.append(ButtonPress("25", "a")
buttonlist.append(ButtonPress("5", "b"))

How can I check if within the list any of the objects has a specific time value? I'm trying:

if "25" in buttonlist[:]['time']
    print("yaaay")
else:
    print("feck")

But this does not work.


Solution

  • Use any:

    class ButtonPress():
        def __init__(self, time, button):
            self.time = time
            self.button = button
    
    buttonlist = []
    buttonlist.append(ButtonPress("25", "a"))
    buttonlist.append(ButtonPress("5", "b"))
    
    if any(button.time == "25" for button in buttonlist):
        print("yaaay")
    else:
        print("feck")
    

    Output

    yaaay
    

    An alternative using in is the following:

    if "25" in (button.time for button in buttonlist):