How to Convert Python Set to Tuple
Python Tuples are used to store multiple elements in a single variable. Sets are also used to save multiple elements in a single variable. After creating a tuple, you can not change it, and tuples are unchangeable. Tuples are written in round brackets, and sets are written with curly brackets.
To create a tuple in Python, place all the items in the ( ) parenthesis, separated by commas. To create a Python set, place all the items in the { } parenthesis, separated by commas.
To find how many elements a tuple or set has, use the len() function.
We have already seen how to convert a tuple to a set in this blog. Let’s see how to convert set to tuple in Python with an example.
Convert Python Set to Tuple
To convert Python Set to Tuple, use the tuple() method. The tuple() function takes an iterator as a parameter, and in our case, it is a set, and it returns a tuple.
chilling_adentures = {"Sabrina", "Zelda", "Hilda", "Ambrose"} of_sabrina = tuple(chilling_adentures) print(of_sabrina) print(type(of_sabrina))
Output
('Hilda', 'Ambrose', 'Sabrina', 'Zelda') <class 'tuple'>
To check the data type in Python, use the type() function. We did use the type() function, and it returns the tuple that means our conversion from set to tuple is successful.
Convert Set to Tuple using for loop and tuple()
In this approach, we will convert Set to Tuple, using a custom function that takes a set as an argument and using the for loop to create a tuple from the input set.
def convert(set): return tuple(i for i in set) chilling_adentures = {"Sabrina", "Zelda", "Hilda", "Ambrose"} of_sabrina = convert(chilling_adentures) print(of_sabrina) print(type(of_sabrina))
Output
('Hilda', 'Ambrose', 'Zelda', 'Sabrina') <class 'tuple'>
The convert() function accepts the set as an argument, which returns the tuple.
Convert Set to Tuple using (*set, ) approach.
The (*set, ) approach mainly unpacks the set inside a tuple literal, which is created due to the single comma’s presence (, ). This approach is a bit faster but suffers from readability.
def convert(set): return (*set, ) chilling_adentures = {"Sabrina", "Zelda", "Hilda", "Ambrose"} of_sabrina = convert(chilling_adentures) print(of_sabrina) print(type(of_sabrina))
Output
('Zelda', 'Ambrose', 'Hilda', 'Sabrina') <class 'tuple'>
In this example, the convert() method accepts the set as an argument. Inside the rounded parenthesis, *set unpacks the set element and places it inside the rounded brackets with command separated values and then returns it.
That is it for converting a set to a tuple in Python.