Question

This question already has an answer here:

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"
Was it helpful?

Solution

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.

OTHER TIPS

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.

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top