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.
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:
not intest for membership.
x in sevaluates to true if
xis a member of
s, and false otherwise… All built-in sequences and set types support this as well as dictionary, for which
intests whether the dictionary has a given key. For container types such as list, tuple, set, frozenset, dict, or collections.deque, the expression
x in yis 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! 😀