Q:

Python | Union of Tuples

belongs to collection: Python Tuple Programs

0

Example:

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

Performing the union of Tuple

In this program, we have two tuples with integer elements. Our task is to create a python program to perform the union operation between two tuples.

Input:
tup1 = (3, 7, 1, 9), tup2 = (4, 5, 7, 1)

Output:
(1, 3, 4, 5, 7, 9)

All Answers

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

Method 1:

One way to solve the problem is by using the + operator to perform union operations. The method is performed over sets so we will perform the conversion using set() and tuple() methods.

# Python Program to perform Union of Tuples

# Creating and Printing Union of Tuples 
Tuple1 = (3, 7, 1, 9)
Tuple2 = (4, 5, 7, 1)
print("The elements of Tuple 1 : " + str(Tuple1))
print("The elements of Tuple 2 : " + str(Tuple2))

# performing union operation on Tuples 
unionTuple = tuple(set(Tuple1 + Tuple2))

# Printing union tuple 
print("The elements of Union of Tuples : " + str(unionTuple))

Output:

The elements of Tuple 1 : (3, 7, 1, 9)
The elements of Tuple 2 : (4, 5, 7, 1)
The elements of Union of Tuples : (1, 3, 4, 5, 7, 9)

Method 2:

Another method to perform the union operation is by using the union() method. This method works with sets, so we will be converting the tuples to set using the set() method and then converting the union set back to tuples using the tuple() method.

# Python Program to perform Union of Tuples

# Creating and Printing Union of Tuples 
Tuple1 = (3, 7, 1, 9)
Tuple2 = (4, 5, 7, 1)
print("The elements of Tuple 1 : " + str(Tuple1))
print("The elements of Tuple 2 : " + str(Tuple2))

# Performing union operation on Tuples using union() method 
unionTuple = tuple(set(Tuple1).union(set(Tuple2)))

# Printing union tuple 
print("The elements of Union of Tuples : " + str(unionTuple))

Output:

The elements of Tuple 1 : (3, 7, 1, 9)
The elements of Tuple 2 : (4, 5, 7, 1)
The elements of Union of Tuples : (1, 3, 4, 5, 7, 9)

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 | Rear elements from Tuple Strings... >>
<< Python | Tuple elements inversions...