Search code examples
pythonoopindexingcomparison

Checking instances attributes based on list length and indexing


I'm looking for a pythonic way to write the same code below but in fewer lines:

mylist = [Instance1(), Instance2(), Instance3()]

if mylist[0].skill == 'java' and mylist[0].is_eligible:
    [...]
elif mylist[1].skill == 'java' and mylist[1].is_eligible:
    [...]
elif mylist[2].skill == 'java' and mylist[2].is_eligible:
    [...]

So notice here that I'm using the elif statement and the conditions in the pseudocode above shouldn't occur at once, but only one of them should be executed.

If that wasn't the case, I would just loop on every instance in the list and check the condition easily.

Keep in mind that the number of conditions is equal to the length of the list so it doesn't have to be always equal to 3.

NOTE :

I need to check that condition for the first item , if it's False, I would check it for the second item of the list, if it's True I would stop executing the block of code, and so on ..


Solution

  • You can use break once you find the item that matches:

    for item in mylist:
      if item.skill == 'java' and item.is_eligible:
        print(item)
        break
    else:
      print('No match')