Eric G
Eric G

Reputation: 67

Multiple if statement vs Loop

I have general python best practice question. Below code returns same output, but which one is recommended style and efficient.

if val1 in string1:
    return 'Yes'
if val2 in string1:
    return 'Yes'
if val3 in string1:
    return 'Yes'

lists=[val1,val2,val3]
for l in lists:
    if l in string1:
        return 'Yes'

if val1 in string1 or val2 in string1 or val3 in string1:
    return 'Yes'

Upvotes: 0

Views: 575

Answers (3)

Roshan
Roshan

Reputation: 724

I would probably recommend using the for loop because the syntax is readable by most beginners and it is short. You can edit the for loop easily if in case you want to add more or remove more items.

Upvotes: 1

sun_dare
sun_dare

Reputation: 1166

Totally depends on the context

The first option definitely has lot of redundant code and doesn't scale well if number of vals (val4 ...) that you want to check increases

If you think that you will always be checking only 3 values (val1,val2, val3) your solution three looks cleaner

But option two is recommended. If you think that in you would be checking for more values, you can easily add entries to array/list and iterate it.

Upvotes: 2

John Kugelman
John Kugelman

Reputation: 361615

I'd go with Option D.

if any(val in string1 for val in [val1, val2, val3]):
    return 'Yes'

Upvotes: 5

Related Questions