Python – Convert Set to Tuple

Convert Set to Tuple

Sometimes, because of the differences in how elements are stored in a tuple, or set, we may need to convert a given Set of elements into a Tuple in Python.

In this tutorial, we shall learn how to convert a set into a tuple. There are many ways to do that. And we shall discuss the following methods with examples for each.

1. Convert Set to Tuple using tuple() builtin function

tuple() builtin function can take any iterable as argument, and return a tuple object formed using the elements from the given iterable.

In the following program, we take a set of strings, and convert it into a tuple.

Python Program

# Take a set of elements
mySet = {'apple', 'banana', 'cherry'}

# Convert set to tuple
output = tuple(mySet)
print(f'Tuple : {output}')
Run Code

Output

Tuple : ('banana', 'apple', 'cherry')

2. Convert Set to Tuple by unpacking the Set inside parenthesis

We can also unpack the items of given set inside curly braces to create a tuple.

In the following program, we have a set of strings, and we shall unpack the elements of this set inside parenthesis.

Python Program

# Take a set of elements
mySet = {'apple', 'banana', 'cherry'}

# Unpack set items and form tuple
output = (*mySet,)
print(f'Tuple : {output}')
Run Code

Output

Tuple : ('apple', 'cherry', 'banana')

Summary

In this tutorial of Python Examples, we learned how to convert a Set into a Tuple in different ways, with the help of well detailed example programs.

Related Tutorials

Privacy Policy Terms of Use

SitemapContact Us