views:

352

answers:

7

When using IF statements in Python, you have to do the following to make the "cascade" work correctly.

if job == "mechanic" or job == "tech":
        print "awesome"
elif job == "tool" or job == "rock":
        print "dolt"

Is there a way to make Python accept multiple values when checking for "equals to"? For example,

if job == "mechanic" or "tech":
    print "awesome"
elif job == "tool" or "rock":
    print "dolt"
+19  A: 
if job in ("mechanic", "tech"):
    print "awesome"
elif job in ("tool", "rock"):
    print "dolt"

The values in parentheses are a tuple. The in operator checks to see whether the left hand side item occurs somewhere inside the right handle tuple.

Note that when Python searches a tuple or list using the in operator, it does a linear search. If you have a large number of items on the right hand side, this could be a performance bottleneck. A larger-scale way of doing this would be to use a frozenset:

AwesomeJobs = frozenset(["mechanic", "tech", ... lots of others ])
def func():
    if job in AwesomeJobs:
        print "awesome"

The use of frozenset over set is preferred if the list of awesome jobs does not need to be changed during the operation of your program.

Greg Hewgill
Since you have the accepted answer, it would be nice to also mention the `item in set()` operation for completeness.
ΤΖΩΤΖΙΟΥ
+1  A: 
if job in ("mechanic", "tech"):
    print "awesome"
elif job in ("tool", "rock"):
    print "dolt"
Alexander Kojevnikov
+1  A: 

While I don't think you can do what you want directly, one alternative is:

if job in [ "mechanic", "tech" ]:
    print "awesome"
elif job in [ "tool", "rock" ]:
    print "dolt"
Jason Etheridge
A: 

In other languages I'd use a switch/select statement to get the job done. You can do that in python too.

Oli
+3  A: 

You can use in:

if job  in ["mechanic", "tech"]:
    print "awesome"

When checking very large numbers, it may also be worth storing off a set of the items to check, as this will be faster. Eg.

AwesomeJobs = set(["mechanic", "tech", ... lots of others ])
...

def func():
    if job in AwesomeJobs:
        print "awesome"
Brian
A: 

I thought it had something to do with tuples but I kept trying to use OR operator in the statement. Naturally it didn't work.

Thanks.

crystalattice
+1  A: 

Tuples with constant items are stored themselves as constants in the compiled function. They can be loaded with a single instruction. Lists and sets on the other hand, are always constructed anew on each execution.

Both tuples and lists use linear search for the in-operator. Sets uses a hash-based look-up, so it will be faster for a larger number of options.

MizardX