How To Test On Variable Against Multiple Values In Python
How to test one variable against multiple values in Python
Akbar S. Ahmed | Feb 24, 2015

Hands-on coding

Sometimes you need to check a variable against multiple values. For example, if the value of x is 1, 3, or 5 then do something. The inverse example is if the variables x, y, or z equal 5 then do something.

Solving both of these issues is simple in Python and does not require a series of if statements.

Solution explanation

The Python in operator performs a membership test by iterating over an iterable. A tuple is an iterable.

Test one variable against multiple values

First, enter the python interpreter.

python

The solution involves a single if statement where we test our variable against a tuple that contains multiple values.

>>> x = 3
>>>
>>> if x in (1, 3, 5):
...     print 'found x'
...
found x

Explanation

in loops over the values in the tuple to check if the variable equals any of the values. Internally, python is running the if statement as:

if x = 1 or x = 3 or x = 5

Test one value against multiple variables

First, enter the python interpreter.

python

Next, we’ll define three variables and our if statement.

>>> x = 3
>>> y = 5
>>> z = 7
>>>
>>> if 3 in {x, y, z}:
...     print 'found it'
...
found it

Elaboration

in loops over the variables in the tuple to check if any variable is equal to the value. Internally, python is running the if statement as:

if 3 = x or 3 = y or 3 = z



Subscribe to our newsletter

Contact Information

ABOUT EXPONENTIAL.IO

We specialize in helping professional developers, like you, expand your skill set. Our courses are focused on enabling you to learn everything necessary to use a new technology in a live, production application.

LOCATION

All courses are made with love in
Palo Alto, CA.

Subscribe to our newsletter