Check if tuple and list are identical in Python

PythonServer Side ProgrammingProgramming

When it is required to check if a tuple and a list are identical, i.e they contain same elements, a simple loop can be used.

A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on).

Below is a demonstration of the same −

Example

Live Demo

my_tuple_1 = ('Hi' , 'there', 'Will')
my_list = ['How' ,'are' ,'you']

print("The tuple is : ")
print(my_tuple_1)
print("The list is : ")
print(my_list)

my_result = True
for i in range(0, len(my_list)):
   if(my_list[i] != my_tuple_1[i]):
      my_result = False
      break
print("Are the tuple and list identical ? ")
print(my_result)

Output

The tuple is :
('Hi', 'there', 'Will')
The list is :
['How', 'are', 'you']
Are the tuple and list identical ?
False

Explanation

  • A tuple and a list are defined and displayed on the console.
  • A variable is assigned the 'True' value.
  • The list is iterated over, and every element from the list and the tuple are compared.
  • If they are not same, the variable that was previously assigned 'True' is assigned a 'False' value.
  • It breaks out of the loop.
  • The final result is the Boolean value stored in the variable.
  • It is displayed on the console
raja
Published on 12-Mar-2021 10:26:52
Advertisements