How to Test Multiple Variables Against a Value?

Rate this post

To test multiple variables x, y, z against a value v, use the set membership operation v in {x, y, z} that leverages the in keyword to check if the value v matches any value in the set {x, y, z}. The return value is a Boolean and the runtime complexity is O(1) to check the membership and O(n) to create the temporary set.

The Cause of Errors

Many beginner programmers struggle with writing a condition which compares many variables to an integer or to a string. In this tutorial, you will find several ways to prevent problems with conditions like this:

x, y, z = 2, 3, 4

print('Test!')

if x or y or z == 1:
    print('We do not want this line of code to be printed out.')

Output:

Test!
We do not want this line of code to be printed out.

We may now be confused and ask why our program is not working? After all, there should be no result! However, there is, and the reason is simple, because the condition is met when at least one value is True, and in our code, even two conditions are met, you could ask: How?
They are met because when we write a condition this way:

if x or y or z == 1:
    # your code here

Python sees this line in a slightly different way than we do, namely the value x and y is not 2 and 3 in this case, but True and True, so our program works, but not as we would like it to work.

So how to make our program work the way we planned it to? Fortunately, there are a couple of methods to do it. You can get a quick overview in our interactive shell:

Exercise: Run the shell and check if the output is the same for all four methods. Now, dive into each method by reading on in the article!

Method 1: Individual Conditions

Correct the line that checks if each variable meets the conditions by adding a condition to each variable manually, in this case replace x or y or z == 1 to x == 1 or y == 1 or z == 1.

print('Test!')
if x == 1 or y == 1 or z == 1:
    print('We do not want this line of code to be printed out')

Output:

Test!

As we can see, now our script works correctly, but with larger programs it would take a lot of time, however there are more effective methods.

Method 2: Membership

In Python, we can write a condition using the tuple, this is a faster way than adding the same condition to every variable in the checking line. In our case, the code would look in the following way:

print('Test!')
if 1 in (x, y, z):
    print('We do not want this line of code to be printed out')

Output:

Test!

This is a way that takes up less space and is faster, but if you want to check if a condition is met in more variables, then it would be an even better idea to use the set, because the set does not allow the same values to appear in it. Simply change (โ€ฆ) to {โ€ฆ}.

Method 3: Dictionary

Sometimes we can also use a dictionary. Depending on what our program does, it may be a good choice, for example, if you want to add a letter based on the value of a variable to the list, you should use a dictionary instead of writing the program this way:

x, y, z, mylist = 1, 2, 3, []

if 1 in {x, y, z}:
    mylist.append("A")
if 2 in {x, y, z}:
    mylist.append("X")
if 3 in {x, y, z}:
    mylist.append("E")

If you use a dictionary, it would look like this:

x, y, z, mylist = 1, 2, 3, []

numbers_to_letters = {1: "A", 2: "X", 3: "E"}
for number in numbers_to_letters:
    if number in {x, y, z}:
        mylist.append(numbers_to_letters[number])

The output will be the same (AXE), but the dictionary looks better and when you have to write a larger program, writing will take less time.

Method 4: One-Liner

And what if we want to write a one-line solution? There is also a way to do it with list comprehension! And it looks like this:

mylist = [{1: 'A', 2: 'X', 3: 'E'}[i] for i in [0, 1, 2, 3] if i in (x, y, z)]

At the beginning, a list is created and then a for loop goes through the values 1, 2, 3 and checks if these numbers are equal to any of the variables. If so, depending on what value i represents, it adds a letter to the list which can be found in the dictionary, e.g. if i = 1 and one of the variables is also equal to 1, then the letter A is added to the list called mylist and so on.

Summary

We learned why you cannot write conditions like this: if x or y or z == 1 and how to write such conditions correctly, and also what to do if you want to add, for example, letters that meet our condition to the list.ย 

I hope this blog article has helped you to understand the possible cause of an inaccurate result due to an incorrectly written condition and provided you with a suitable method.

Where to Go From Here?

Enough theory. Letโ€™s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. Thatโ€™s how you polish the skills you really need in practice. After all, whatโ€™s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

๐Ÿš€ If your answer is YES!, consider becoming a Python freelance developer! Itโ€™s the best way of approaching the task of improving your Python skillsโ€”even if you are a complete beginner.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar โ€œHow to Build Your High-Income Skill Pythonโ€ and learn how I grew my coding business online and how you can, tooโ€”from the comfort of your own home.

Join the free webinar now!