
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check If Two Lists of Tuples Are Identical in Python
Lists of Tuples in Python
A tuple is a built-in Python data structure for storing multiple items in a single variable. While both tuples and lists can organize ordered collections of items, tuples are immutable, whereas lists are mutable.
A list can store heterogeneous values, including various types of data such as integers, floating-point numbers, strings, and more. A list of tuples refers to tuples encapsulated within a list.
Comparing Lists of Tuples
The '==' operator is used to compare two iterables and determine if they are equal. It is used to check whether two lists are equal. Therefore, we can use the same to verify whether two lists of tuples are identical.
Example
This code compares two lists of tuples using the '==' operator. It checks if all the elements in both lists are identical, outputs the lists, and prints the comparison result.
my_list_1 = [(11, 14), (54, 58)] my_list_2 = [(98, 0), (10, 13)] print("The first list of tuple is : ") print(my_list_1) print("The second list of tuple is : ") print(my_list_2) my_result = my_list_1 == my_list_2 print("Are the list of tuples identical ?") print(my_result)
The result is obtained as follows -
The first list of tuple is : [(11, 14), (54, 58)] The second list of tuple is : [(98, 0), (10, 13)] Are the list of tuples identical? False
Tuple Comparison Examples
Tuples are compared sequentially, position by position. The first items of both tuples are compared; if they differ, the result is determined. Otherwise, subsequent items are compared consecutively.
a = [(11, 14), (54, 58)] b = [(98, 0), (10, 13)] print(a < b)
The result is obtained as follows ?
True
Another type of comparison involves identifying similar and distinct elements using sets. Sets extract unique values from tuples, enabling the use of the & operator for intersection to find common elements.
a = [(11, 14), (54, 58), (10, 13)] b = [(98, 0), (10, 13)] print(set(a) & set(b));
We will get the output as follows ?
{(10, 13)}
The result is obtained as the com
The set.intersection() function can also be used for this operation. It converts tuples a and b into sets and identifies the common elements between then using the intersection() method.
a = [(11, 14), (54, 58), (10, 13)] b = [(98, 0), (10, 13)] print(set(a).intersection(set(b)))
The output is produced as follows ?
{(10, 13)}