If you are looking for an instruction to check if multiple variables are equal in Python, keep reading our article. Today, we will provide a few methods to show you how to implement code.
Check if multiple variables are equal in Python
Compare discrete variables by the operator “==”
Like other programming languages, you can use the operator “==” to compare two variables. Moreover, you can still use it to compare multiple variables. The variables can be an integer, a string, a list, a dictionary, etc. The result is a boolean value. True if all the variables are equal to each other. Otherwise, the result is false.
var1 == var2 == var3 == … == varN
Detailed implementation in the following code:
myTuple = (1, 2, 3, 4, 5) myList = [1, 2, 3, 4, 5] myInt = 2 # Compare the second element of the tuple, the list, and the number print(myTuple == myList == myInt )
Compare elements of an iterable by the function all()
In this part, we will introduce you to compare many elements in an iterable with the function all(). The function returns true if all the elements or conditions are true, otherwise returns false.
In the example below, we use the function to compare all the elements with the first element. If they are equal to the first element, they are all the same. So, the result of the function will be true. We also use list comprehension techniques to traverse the list.
myList = [3, 3, 3, 3, 3, 3] # Compare all elements of the list with the first element print (all(element == myList for element in myList))
Compare elements of an iterable by the operator “==”
We all know how to use the operator “==” to compare multiple variables in the first part. Now we will use the operator to compare an iterable’s elements.
myList = [3, 3, 3, 3, 3, 3] # Function to check if all elements are equal def check_equal(aList): # Loop the list for i in aList: # Compare each element with the first element return false if there is a different value if i != aList: return False return True print(check_equal(myList))
Our tutorial provides detailed examples to check if multiple variables are equal in Python. If you want to compare discrete variables, use the operator “==”, and if you compare multiple elements of an iterable such as a list, use the function all().
Maybe you are interested:
- Check if a variable is not Null in Python
- Check if a variable is Null in Python
- Test multiple variables against a single value in Python
My name is Robert Collier. I graduated in IT at HUST university. My interest is learning programming languages; my strengths are Python, C, C++, and Machine Learning/Deep Learning/NLP. I will share all the knowledge I have through my articles. Hope you like them.
Name of the university: HUST
Programming Languages: Python, C, C++, Machine Learning/Deep Learning/NLP