Python – Comparing against multiple items

I see this scenario and solution more often than I probably should: you have a value that needs to be compared against multiple possible values, and if there is a match perform a certain action. Usually the solution to this common event is to create a series of if...elif...else conditions, one for each possible value, running the commands after each passing condition, and using the else clause as the non matching case. An example of such a condition would be like so:

favoriteCandy = "Sweetarts"
if favoriteCandy == "Snickers":
    eatCandy(favoriteCandy)
elif favoriteCandy == "M&M's":
    eatCandy(favoriteCandy)
elif favoriteCandy == "REESE'S":
    eatCandy(favoriteCandy)
elif favoriteCandy == "Sweetarts":
    eatCandy(favoriteCandy)
else:
    print("So then what is your favorite candy?")

However, I am here to explain to you clearly a better and more excellent way to handle this situation.

Instead of the conditional chain as shown above, store all the possible values within a tuple or list then use the in expression on the array, like so:

favoriteCandy = "Sweetarts"
if favoriteCandy in ("Snickers", "M&M's", "REESE'S", "Sweetarts"):
    eatCandy(favoriteCandy)
else:
    print("So then what is your favorite candy?")

Allow me to quote the Python docs on why this works:

The operators in and not in test for membership. x in s evaluates to true if x is a member of s, and false otherwise… All built-in sequences and set types support this as well as dictionary, for which in tests whether the dictionary has a given key. For container types such as list, tuple, set, frozenset, dict, or collections.deque, the expression x in y is equivalent to any(x is e or x == e for e in y).

In simpler terms, this works because in performs membership testing on the array, returning True if the item is in the tuple/list and False if not. To provide a third equivalent code example, our simplified if x in y example could also be written using a for loop as shown:

favoriteCandyEaten = False
favoriteCandy = "Sweetarts"
for item in ("Snickers", "M&M's", "REESE'S", "Sweetarts"):
    if item == favoriteCandy:
        eatCandy(favoriteCandy)
        favoriteCandyEaten = True
        break

if not favoriteCandyEaten:
    print("So then what is your favorite candy?")

Finally, when deciding on using a list or tuple in your condition, here are a few pointers.

  • If that particular array items needs to be referenced again, assign it to a variable and use that in your condition. Naturally, it will still work.
  • If the set needs to be edited anytime after it is initialized, use a list. Otherwise, use a tuple, which, recall, cannot be edited after being created.

Congratulations! You now know how to compare a single value against multiple possible values without using a long conditional chain! 😀
-le717

Advertisements

Triangular Reactions

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s