Q:

Python program to perform tuple intersection in list (order irrespective)

belongs to collection: Python Tuple Programs

0

Example:

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

List is a sequence data type. It is mutable as its values in the list can be modified. It is a collection of an ordered set of values enclosed in square brackets []

Example:

list = [3 ,1,  5, 7]

Here, we are given two lists consisting of tuple elements. And we need to perform intersection in the list i.e., find the tuple from which is present in both the list in Python.

Input:
tupList1 = [(8, 1), (5, 10)], tupList2 = [(6, 3), (10, 5)]

Output:
{(5, 10)}

To solve this problem, we will be traversing both lists to tuples to find all the tuples which are common in both. For checking for common tuples, we will not consider the order of elements in the tuple.

All Answers

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

Method 1:

We will sort the tuples (we need to find common tuples irrespective of order). Then perform intersection operations on lists using & operator.

# Python program to perform tuple intersection 
# in lists

# Creating and printing both lists
myTupleList1 = [(8, 1), (5, 10)]
myTupleList2 = [(6, 3), (10, 5)]
print("Tuple List 1 : " + str(myTupleList1))
print("Tuple List 2 : " + str(myTupleList2))

# Performing tuple intersection in List 
intersection = set([tuple(sorted(vals)) for vals in myTupleList1]) & set([tuple(sorted(vals)) for vals in myTupleList2])

# printing intersection set 
print("Intersection of both list : " + str(intersection))

Output:

Tuple List 1 : [(8, 1), (5, 10)]
Tuple List 2 : [(6, 3), (10, 5)]
Intersection of both list : {(5, 10)}

Method 2:

Another way to solve the problem is by converting the tuples to sets (which are ordered) and then do the intersection of these sets using frozenset and map it to get the resultant.

# Python program to perform tuple intersection 
# in lists

# Creating and printing both lists
myTupleList1 = [(8, 1), (5, 10)]
myTupleList2 = [(6, 3), (10, 5)]
print("Tuple List 1 : " + str(myTupleList1))
print("Tuple List 2 : " + str(myTupleList2))

# Performing tuple intersection in List 
intersection = set(map(frozenset, myTupleList1)) & set(map(frozenset, myTupleList2))

# printing intersection set 
print("Intersection of both list : " + str(intersection))

Output:

Tuple List 1 : [(8, 1), (5, 10)]
Tuple List 2 : [(6, 3), (10, 5)]
Intersection of both list : {frozenset({10, 5})}

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 convert binary tuple to integer... >>
<< Python program to extract tuples with all numeric ...