Skip to content
Home » How To Convert Python Set into Tuple | Python

How To Convert Python Set into Tuple | Python

In this tutorial let’s learn about How To Convert Python Set into Tuple. Let’s look into different ways of converting a set into tuple in python.

Tuple and Set in Python

Tuples are used in Python to hold several elements in a single variable. Sets are also useful for storing several components in a single variable. You cannot edit a tuple once it has been created, and tuples are unchangeable. Sets are expressed in curly brackets, while tuples are written in round brackets.

To construct a tuple in Python, put all of the things inside the () parenthesis, separated by commas. To create a Python set, put all of the items in {} separated by commas.

Convert Python Set into Tuple using tuple() Method

Use the tuple() function to convert a Python Set to a Tuple. The tuple() function accepts an iterator as an input (in this case, a set) and returns a tuple.

Method:

tuple() : To convert into a tuple, use the tuple method. Other type values can be passed as arguments to this method, which returns a tuple type value.

Code Example :

# program to convert set to tuple

s = {'a', 'b', 'c', 'd'}
print(type(s), s)

# tuple() method
t = tuple(s)

# print tuple
print(type(t), t)

Output :

<class ‘set’> {‘d’, ‘a’, ‘b’, ‘c’}
<class ‘tuple’> (‘d’, ‘a’, ‘b’, ‘c’)

Convert Set to Tuple without using tuple() method in Python

The (*set_variable,) technique primarily unpacks the set into a tuple literal, which is generated by the presence of a single comma (, ). This method is a little faster than the tuple() method.

Code Example :

# program to convert set to tuple without using tuple() method

s = {'a', 'b', 'c', 'd'}
print(type(s), s)

# (*s,) method
t = (*s,)

# print tuple
print(type(t), t)

Output :

<class ‘set’> {‘d’, ‘a’, ‘b’, ‘c’}
<class ‘tuple’> (‘d’, ‘a’, ‘b’, ‘c’)

Convert a Set into Tuple using for loop in Python

In this approach we will be looping into each element of the set and converting them into tuple. It is time consuming approach than the methods discussed above.

Code Example :

# program to convert set to tuple

s = {'a', 'b', 'c', 'd'}
print(type(s), s)

# for loop and tuple method
t = tuple(i for i in s)

# print tuple
print(type(t), t)

Output :

<class ‘set’> {‘d’, ‘a’, ‘b’, ‘c’}
<class ‘tuple’> (‘d’, ‘a’, ‘b’, ‘c’)

Conclusion

In this tutorial we learnt different ways to convert the set into tuple in python. Also discussed the time complexities and confirmed that (*set_variable,) looks bit faster than the remaining approaches.

Similar Posts:

How to Convert String to Float in Python
How to Convert Bytes to String in Python
How to Convert a List to String in Python