0

I want to use if condition for elements of the given list:

list = ['apple','banana','carrot']

for i in list:
    if i == 'apple' or 'banana': ##Here is problem!
        print i, 'pass'

The result is wrong:

apple pass
banana pass
carrot pass

It should be:

apple pass
banana pass

The no of elements to be tested in my problem are large, so looking for better way of handling it.

Roman
  • 2,587
  • 8
  • 23
  • 51

1 Answers1

2

The issue is in line -

if i == 'apple' or 'banana':

You are checking if i == 'apple' or if 'banana' is true. All strings are true, so if you do -

if 'banana':

It will always evaluate to true, and hence you are getting the issue of all values getting printed.

You need to do -

if i == 'apple' or i == 'banana':

Or you can also do -

if i in ['apple','banana']:
Anand S Kumar
  • 82,977
  • 18
  • 174
  • 164