Python | Check if tuple and list are identical

Sometimes while working with different data in Python, we can have a problem of having data in different containers. In this situations, there can be need to test if data is identical cross containers. Let’s discuss certain ways in which this task can be performed.

Method #1 : Using loop
This is the brute force method to perform this particular task. In this, we just iterate for list and tuple to test if at each index the elements are similar.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Check if tuple and list are identical
# Using loop
  
# Initializing list and tuple
test_list = ['gfg', 'is', 'best']
test_tup = ('gfg', 'is', 'best')
  
# printing original list and tuple 
print("The original list is : " + str(test_list))
print("The original tuple is : " + str(test_tup))
  
# Check if tuple and list are identical
# Using loop
res = True
for i in range(0, len(test_list)):
    if(test_list[i] != test_tup[i]):
        res = False
        break
  
# printing result
print("Are tuple and list identical ? : " + str(res))

chevron_right


Output :



The original list is : ['gfg', 'is', 'best']
The original tuple is : ('gfg', 'is', 'best')
Are tuple and list identical ? : True

 

Method #2 : Using all() + zip()
This task can also be performed in a single line using combination of above functions. In this, we just combine the container elements using zip(), and use all() to test for equality of elements at corresponding index.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Check if tuple and list are identical
# Using all() + zip()
  
# Initializing list and tuple
test_list = ['gfg', 'is', 'best']
test_tup = ('gfg', 'is', 'best')
  
# printing original list and tuple 
print("The original list is : " + str(test_list))
print("The original tuple is : " + str(test_tup))
  
# Check if tuple and list are identical
# Using all() + zip()
res = all( [i == j for i, j in zip(test_list, test_tup)] )
  
# printing result
print("Are tuple and list identical ? : " + str(res))

chevron_right


Output :

The original list is : ['gfg', 'is', 'best']
The original tuple is : ('gfg', 'is', 'best')
Are tuple and list identical ? : True



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.