Python if/elif simplification

280 views Asked by At

This is part of my code:

for line in f:
    if animals[0].upper() in line:
        break
    elif animals[1].upper() in line:
        break
    elif animals[2].upper() in line:
        break
    elif animals[3].upper() in line:
        break
    elif animals[4].upper() in line:
        break
    elif animals[5].upper() in line:
        break
    elif animals[6].upper() in line:
        break
    elif animals[7].upper() in line:
        break
    elif animals[8].upper() in line:
        break
    elif animals[9].upper() in line:
        break
    elif animals[10].upper() in line:
        break
    print(line)

I'm just trying to figure if it can be simplified somehow but I really can't come up with anything. Any thoughts?

Thanks!

1

There are 1 answers

5
mgilson On

Here's a completely equivalent piece of code to what you have above:

if any(animals[x].upper() in line for x in range(11)):
    break

Assuming that animals supports the iterator protocol (which is likely true), an even better solution would be to do something like this:

if any(animal.upper() in line for animal in animals):  # slice animals as necessary
    break