How To Check If Multiple Variables Are Equal In Python

Check if multiple variables are equal in Python

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. 

Syntax:

var1 == var2 == var3 == … == varN

Detailed implementation in the following code:

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[1] == myList[1] == myInt )

Result:

True

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.

Code:

myList = [3, 3, 3, 3, 3, 3]
 
# Compare all elements of the list with the first element
print (all(element == myList[0] for element in myList))

Result:

True

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. 

Code:

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[0]:
      return False      
  return True
 
print(check_equal(myList))

Result:

True

Summary

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:

Leave a Reply

Your email address will not be published. Required fields are marked *