Python program to convert Set into Tuple and Tuple into Set

PythonServer Side ProgrammingProgramming

When it is required to convert a set structure into a tuple, and a tuple into a set, the ‘tuple’ and ‘set’ methods can be used.

Below is a demonstration of the same −

Example

 Live Demo

my_set = {'ab', 'cd', 'ef', 'g', 'h', 's', 'v'}
print("The type is : ")
print(type(my_set), " ", my_set)
print("Converting a set into a tuple")
my_tuple = tuple(my_set)
print("The type is : ")
print(type(my_tuple), " ", my_tuple)
my_tuple = ('ab', 'cd', 'ef', 'g', 'h', 's', 'v')
print("The tuple is:")
print(my_tuple)
print(type(my_tuple), " ", my_tuple)
print("Converting tuple to set")
my_set = set(my_tuple)
print(type(my_set), " ", my_set)

Output

The type is :
<class 'set'> {'ef', 'g', 'h', 's', 'ab', 'v', 'cd'}
Converting a set into a tuple
The type is :
<class 'tuple'> ('ef', 'g', 'h', 's', 'ab', 'v', 'cd')
The tuple is:
('ab', 'cd', 'ef', 'g', 'h', 's', 'v')
<class 'tuple'> ('ab', 'cd', 'ef', 'g', 'h', 's', 'v')
Converting tuple to set
<class 'set'> {'ef', 'g', 'h', 's', 'ab', 'v', 'cd'}

Explanation

  • A set is defined and is displayed on the console.

  • The type of this data structure is determined using the ‘type’ method.

  • It is converted to a tuple using the ‘tuple’ method.

  • The type of this type is determined using the ‘type’ method.

  • Now to convert this tuple back to set, the ‘set’ method is used.

  • This type is determined and is displayed as the output on the console.

raja
Published on 14-Apr-2021 12:34:34
Advertisements