Check if variable is not equal to multiple values in Python

avatar

Borislav Hadzhiev

Last updated: Aug 12, 2022

banner

Photo from Unsplash

Check if variable is not equal to multiple values in Python #

Use the not in operator to check if a variable is not equal to multiple values, e.g. if my_str not in multiple_values:. The not in operator will return True if the variable is not equal to any of the specified values and False otherwise.

main.py
my_str = 'one' multiple_values = ['two', 'three', 'four'] if my_str not in multiple_values: print('The variable is NOT equal to any of the specified values') else: print('The variable is equal to one or more of the specified values') print(my_str not in multiple_values) # 👉️ True

We used the not in operator to check if a variable is not equal to multiple values.

The in operator tests for membership. For example, x in l evaluates to True if x is a member of l, otherwise it evaluates to False.

x not in l returns the negation of x in l.

The if block will run only if the variable is not equal to any of the specified values, otherwise the else block runs.

Alternatively, you can use the all() function.

Use the all() function to check if a variable is not equal to multiple values, e.g. if all(my_str != item for item in multiple_values):. The all() function will return True if the variable is not equal to any of the values and False otherwise.

main.py
my_str = 'one' multiple_values = ['two', 'three', 'four'] if all(my_str != item for item in multiple_values): print('The variable is NOT equal to any of the specified values') else: print('The variable is equal to one or more of the specified values') # 👇️ True print(all(my_str != item for item in multiple_values))

We used a generator expression to iterate over the list.

Generator expressions are used to perform some operation for every element or select a subset of elements that meet a condition.

On each iteration, we check if the variable is not equal to the current value and return the result.

The all() built-in function takes an iterable as an argument and returns True if all elements in the iterable are truthy (or the iterable is empty).

main.py
my_str = 'one' multiple_values = ['two', 'three', 'four'] # 👇️ True print(all(my_str != item for item in multiple_values))

If the all() function finds a value that is equal to the variable, it will short-circuit returning False.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.