- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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.
Advertisements