Python Tricks: Check Multiple Variables against Single Value

https://miro.medium.com/max/1200/0*fqmjRteitwrk4WHI

Original Source Here

Python Tricks: Check Multiple Variables against Single Value

How to compare multiple variables with a single value at once?

Welcome to a series of short posts each with handy Python tricks that can help you become a better Python programmer. In this blog, we will look into variable comparisons.

Situation

You have variables x, y, z, and you have also got a constant c that you would like to check whether it exists in any of the three variables. We can do it with a brute-force approach with the following logic, but are there better solutions?

if (x == c) or (y == c) or (z == c):
print("It exists!")
else:
print("It does not exist!")

Could-be Solution: Iterator

if any(i == c for i in (x, y, z)):
print("It exists!")
else:
print("It does not exist!")

If in case you would like to check whether all of x, y, z are of value c, you can also change any to all. The two functions check whether any/all of the provided iterator is evaluated as True. That means if we have a tuple of t = (0, 1, 2), all(t) will return False as the first element 0 will be evaluated as False. This also opens up a lot of flexibility as common values like 0, None, [], (), "", {} would all be evaluated as False.

Note that x, y, z have been combined to a tuple rather than a list for marginally better memory performance. If you would like to read more about the memory usage of data structures, I have previously written a piece on it:

Better Solution: Membership Test with Iterable

Instead of creating a tuple and iterate it through, we can also just do it with a membership test and skip the need of any.

# Membership test with list
if c in [x, y, z]:
print("It exists!")
else:
print("It does not exist!")
# Membership test with tuple
if c in (x, y, z):
print("It exists!")
else:
print("It does not exist!")
# Membership test with set
if c in {x, y, z}:
print("It exists!")
else:
print("It does not exist!")

Although both list, tuple, and set supports the membership test as they are all iterables in Python, there are minor differences when choosing which one to use. For example, as tuple is immutable, it should take up the least memory among the three. On the other hand, implementation of set allows constant-cost membership test meaning that it has the least computational complexity among the three. While for list, there just isn’t any edge of using a doubly-linked list in this context so forget about it.

AI/ML

Trending AI/ML Article Identified & Digested via Granola by Ramsey Elbasheer; a Machine-Driven RSS Bot

%d bloggers like this: