Kodeclik Blog


How to convert a set to a tuple in Python

Sometimes you are given a Python set and you desire to convert it into a tuple. Note that sets are unordered and cannot contain duplicates. But sets are mutable, meaning once assigned a set variable can be changed. Tuples have the exact opposite properties. They can contain duplicates and the elements of a tuple are ordered (which means you can apply indexing and slicing operators on them). But tuples are immutable unlike sets.
Let us create a simple set using curly brace notation.
We have deliberately created a set with a duplicate element. When the second line prints the set, the output is:
Note that the order has no significance in a set’s definition and thus the output printed is in a different order than when the set was defined.

Method 1: Use a for loop

The first, easy, way to convert a set into a tuple is to loop through the elements of the set and add each to a tuple.
Here is a program to do the same:
The output of this program is:
Note that as the loop cycles through each element we construct a tuple with that element and add it to the running tuple (mytuple).
To convince that the conversion from set to tuple has happened correctly, you can use the following code:
The output is:
Why do we need the comma in the statement inside the for loop? Note what happens if we remove it thus:
The output will be:
Python complains that we are trying to concatenate a string (namely the first element of the set, i.e., “Humpty”) to the tuple “mytuple”. The use of the comma operator essentially makes the string a 1-element tuple allowing it to be added.

Method 2: Use the tuple() function

A second, easier, way to convert a set into a tuple is to use the tuple function. Consider:
The output is:

Method 3: Do set unpacking

This is a variant of the first method where we do set unpacking but inside a tuple construct. We encapsulate this code inside a function and invoke the function as necessary.
The output is, as before:
We have learnt three different ways to convert a set into a tuple. Which one is your favorite?
Interested in more things Python? See our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!
Want to learn Python with us? Sign up for 1:1 or small group classes.

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.
  • ABOUT

Copyright @ Kodeclik 2023. All rights reserved.