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,173
  • 16
  • 110
  • 129
crystalattice
  • 4,913
  • 11
  • 40
  • 56

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
  • 890,778
  • 177
  • 1,125
  • 1,260
  • 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
  • 113,117
  • 28
  • 106
  • 111
1
if job in ("mechanic", "tech"):
    print "awesome"
elif job in ("tool", "rock"):
    print "dolt"
Alexander Kojevnikov
  • 17,376
  • 5
  • 46
  • 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,741
  • 5
  • 28
  • 32
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
  • 83,508
  • 19
  • 134
  • 137
0

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

Oli
  • 228,145
  • 62
  • 212
  • 294