Q:

Python program to check if two lists of tuples are identical or not

belongs to collection: Python Tuple Programs

0

Example:

tuple = ("python", "includehelp", 43, 54.23)

Check if Two Lists of tuples are identical or not

We are given two tuple lists consisting of integer elements. We need to create a Python program to check whether the given tuple lists are identical i.e. consist of the same set of elements and the same position or not. And return true or false accordingly.

Input:
tupList1 = [(2, 9) ,(5, 6)] ; tupList2 = [(2, 9) ,(5, 6)]
Output:
true

Input:
tupList1 = [(2, 9) ,(5, 6)] ; tupList2 = [(1, 5) ,(5, 6)]
Output:
false

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Method 1:

One method that can accomplish that task is using the equality operator '=='. It returns a boolean value based on the equality of the two collections in python.

# Python program to check if two lists of 
# tuples are identical or not

# Initializing and printing list of tuples
tupList1 = [(10, 4), (2, 5)]
tupList2 = [(10, 4), (2, 5)]
print("The elements of tuple list 1 : " + str(tupList1))
print("The elements of tuple list 2 : " + str(tupList2))

# Checking for identical tuple
isIdentical = tupList1 == tupList2

if(isIdentical) : 
    print("Both Tuple Lists are identical.")
else : 
    print("Both Tuple Lists are not identical.")

Output:

The elements of tuple list 1 : [(10, 4), (2, 5)]
The elements of tuple list 2 : [(10, 4), (2, 5)]
Both Tuple Lists are identical.

Method 2:

Another method that can accomplish the task is by using cmp() method from the python library. This method returns the difference of both collections and 0 (falsy value ) if they are identical.

Using this result we can check if both tuple lists are identical or not.

Note: The cmp() method is supported in Python 2.

# Python program to check if two lists of 
# tuples are identical or not

# Initializing and printing list of tuples
tupList1 = [(10, 4), (2, 5)]
tupList2 = [(10, 4), (2, 5)]
print("The elements of tuple list 1 : " + str(tupList1))
print("The elements of tuple list 2 : " + str(tupList2))

# Checking for identical tuple
isNotIdentical = cmp(tupList1,tupList2)

if(not isNotIdentical) : 
    print("Both Tuple Lists are identical.")
else : 
    print("Both Tuple Lists are not identical.")

Output:

The elements of tuple list 1 : [(10, 4), (2, 5)]
The elements of tuple list 2 : [(10, 4), (2, 5)]
Both Tuple Lists are identical.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Tuple Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to filter tuples according to list ... >>
<< Python program to repeat tuples N times...