16

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"
Quinn Taylor
  • 44,553
  • 16
  • 113
  • 131
crystalattice
  • 5,031
  • 12
  • 40
  • 57

6 Answers6

39
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
  • 951,095
  • 183
  • 1,149
  • 1,285
  • Since you have the accepted answer, it would be nice to also mention the `item in set()` operation for completeness. – tzot Sep 29 '08 at 16:00
4

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
  • 116,865
  • 28
  • 107
  • 112
1
if job in ("mechanic", "tech"):
    print "awesome"
elif job in ("tool", "rock"):
    print "dolt"
Alexander Kojevnikov
  • 17,580
  • 5
  • 49
  • 46
1

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
  • 6,849
  • 5
  • 30
  • 33
1

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.

Markus Jarderot
  • 86,735
  • 21
  • 136
  • 138
0

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

Oli
  • 235,628
  • 64
  • 220
  • 299