Python program to convert Set into Tuple and Tuple into Set


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.

Updated on: 14-Apr-2021

370 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements