Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using OR comparisons with IF statements [duplicate]

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"
like image 627
crystalattice Avatar asked Sep 29 '08 09:09

crystalattice


1 Answers

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.

like image 62
Greg Hewgill Avatar answered Oct 26 '22 14:10

Greg Hewgill