A Set is an unordered collection of unique, mutable values that cannot contain duplicates. On the other hand, a Tuple is an ordered, immutable collection of elements. Conversion between them is a common operation.
Converting Set to Tuple
For the conversion of Set to Tuple, you can use the tuple() constructor and pass the input set as an argument.

What happens behind the scenes is that Python creates a new empty tuple and iterates through each element currently present in the set.
Since a set has no inherent order, elements from the set are retrieved arbitrarily and appended to a new tuple. Once all the elements have been processed, it will return a new tuple containing all the elements.
Since the set does not contain duplicate elements and has unordered elements, the output tuple will have unique elements and unordered elements, too.
new_set = {19, 11, 21, 18} print(new_set) # {19, 18, 11, 21} print(type(new_set)) # <class 'set'> converted_tuple = tuple(new_set) print(converted_tuple) # (19, 18, 11, 21) print(type(converted_tuple)) # <class 'tuple'>
The above code shows that we convert the input set to a tuple and verify it by printing its data type using the type() function.
Ensuring order

To get an ordered tuple from a set, you can use the built-in sorted() function and then convert it using the tuple() constructor.
new_set = {19, 11, 21, 18} print(new_set) # {19, 18, 11, 21} # Ensuring order sorted_tuple = tuple(sorted(new_set)) print(sorted_tuple) # (11, 18, 19, 21)
The sorted() function sorts the set, and then we attempt to convert it.
Converting Tuple to Set
The built-in tuple() constructor converts a tuple into a set.

Under the hood, Python will create a new Set object backed by a hashtable and iterate through the tuple’s elements in their defined order.
For each element, Python checks if it is hashable. If it is not, it will raise a TypeError. If they are hashable, it checks for duplicate values. If the element is not already in the Set, it will be added to the hashtable.
Since the set is an unordered collection, the output should also be unordered. However, if your tuple contains duplicate values, the set will remove duplicates and only contain unique elements.
# Converting tuple to set your_tuple = (19, 21, 21, 18) print(your_tuple) # (19, 21, 21, 18) print(type(your_tuple)) # <class 'tuple'> your_set = set(your_tuple) print(your_set) # {18, 19, 21} print(type(your_set)) # <class 'set'>
Handling unhashable elements
To avoid the TypeError for unhashable elements, you can use the try/except mechanism.
tuple_list = ([19, 21], 3) try: output_set = set(tuple_list) # Raises TypeError except TypeError as e: print("Error:", e) # Error: unhashable type: 'list'That’s all!