Q:

Python | Tuple List Intersection

belongs to collection: Python Tuple Programs

0

Example:

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

Tuple Intersection

The intersection of tuples is finding common elements from both the tuples i.e. the intersection tuple consists of all elements that are common in both the tuples.

In this program, we are given two tuples. We need to create a python program to return a tuple that contains the intersection elements i.e. elements that are common in both tuples.

Input:
tuple1 = (4, 1, 7, 9, 3, 5) , tuple2 = (2, 4, 6, 7, 8)

Output:
(4, 7)

All Answers

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

Method 1:

One method to perform tuple intersection is by performing set intersection operation "&" which will find the intersection of sets. And we will be performing interconversion from a tuple to set and set to a tuple using set() and tuple() methods.

# Program to perform tuple intersection 
# using & operation, 

# initialising and Printing tuples 
myTup1 = (4, 1, 7, 9, 3, 5)
myTup2 = (2, 4, 6, 7, 8)
print("The elements in tuple 1 : " + str(myTup1))
print("The elements in tuple 2 : " + str(myTup2))
  
# Performing intersection operation 
intTuple = tuple(set(myTup1) & set(myTup2))
  
# Result of intersection operation
print("The elements of intersection of their tuples : " + str(intTuple))

Output:

The elements in tuple 1 : (4, 1, 7, 9, 3, 5)
The elements in tuple 2 : (2, 4, 6, 7, 8)
The elements of intersection of their tuples : (4, 7)

Method 2:

Another method to solve the problem is by using the intersection() method in place of & operator on sets. In this program also the interconversion is done using the set() method and the tuple() method.

# Program to perform tuple intersection 
# using & operation, 

# initialising and Printing tuples 
myTup1 = (4, 1, 7, 9, 3, 5)
myTup2 = (2, 4, 6, 7, 8)
print("The elements in tuple 1 : " + str(myTup1))
print("The elements in tuple 2 : " + str(myTup2))
  
# Performing intersection operation 
intTuple = tuple(set(myTup1).intersection(set(myTup2)))
  
# Result of intersection operation
print("The elements of intersection of their tuples : " + str(intTuple))

Output:

The elements in tuple 1 : (4, 1, 7, 9, 3, 5)
The elements in tuple 2 : (2, 4, 6, 7, 8)
The elements of intersection of their tuples : (4, 7)

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 | Records with Value at K index... >>
<< Python | Filter Range Length Tuples...