Python – Convert Tuple to Set

Convert Tuple to Set

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

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

  • Use set() builtin function.
  • Unpack Tuple inside curly braces.

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

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

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

Python Program

# Take a tuple of elements
myTuple = ('apple', 'banana', 'cherry')

# Convert tuple into set
output = set(myTuple)
print(f'Set : {output}')
Run Code Copy

Output

Set : {'cherry', 'banana', 'apple'}

If there are any duplicates in the given tuple object, they are ignored. A set can contain only unique elements.

In the following program, we take a tuple of strings where some of the elements are repeated inside the tuple (duplicates), and convert it into a set.

Python Program

# Take a tuple of elements
myTuple = ('apple', 'banana', 'cherry', 'banana')

# Convert tuple into set
output = set(myTuple)
print(f'Set : {output}')
Run Code Copy

Output

Set : {'cherry', 'banana', 'apple'}

2. Convert Tuple to Set by unpacking the Tuple inside curly braces

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

In the following program, we have a tuple of strings, and we shall unpack the elements of this tuple inside curly braces.

Python Program

# Take a tuple of elements
myTuple = ('apple', 'banana', 'cherry', 'banana')

# Unpack tuple items and form set
output = {*myTuple}
print(f'Set : {output}')
Run Code Copy

Output

Set : {'apple', 'banana', 'cherry'}

Summary

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

Related Tutorials

Code copied to clipboard successfully 👍