Using OR comparisons with IF statements [duplicate]

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.


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"

if job in ("mechanic", "tech"):
    print "awesome"
elif job in ("tool", "rock"):
    print "dolt"

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"

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.