0

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.

Georgy
  • 12,464
  • 7
  • 65
  • 73
lte__
  • 7,175
  • 25
  • 74
  • 131

1 Answers1

6

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):
Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76