convert tuple to a set in python

Convert Tuple to a Set in Python – With Examples

In this tutorial, we will look at how to convert a tuple to a set in Python with the help of some examples.

A tuple is a built-in data structure in Python used to store an ordered collection of items. A set, on the other hand, is used to store a collection of objects but it does not preserve any order. Also, a set stores only unique items.

The following are some of the common use-cases when you want to convert a tuple to a set.

  • To use the tuple as a set and perform some set operations.
  • To remove duplicates from the tuple.

Note that you lose the inherent order in the tuple after conversion to a set (since sets are unordered collections).

convert tuple to a set in python

You can use the Python built-in set() function to convert a tuple to a set. Pass the tuple as an argument to the function. It returns a set resulting from the elements of the tuple.

Let’s look at an example.

# create a tuple
t = (2, 5, 1, 3)
# create set from tuple
s = set(t)
# display the set and its type
print(s)
print(type(s))

Output:

{1, 2, 3, 5}
<class 'set'>

Here we create a set from the tuple t above. You can see that the set contains all the elements from the tuple. Also, note that the inherent order of the elements in the tuple is not preserved in the set.

📚 Data Science Programs By Skill Level

Introductory

Intermediate ⭐⭐⭐

Advanced ⭐⭐⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

What if your tuple has duplicate elements? Let’s find out.

# create a tuple
t = (2, 5, 5, 1, 3)
# create set from tuple
s = set(t)
# display the set and its type
print(s)
print(type(s))

Output:

{1, 2, 3, 5}
<class 'set'>

The resulting set contains only the distinct elements from the tuple.

Using sets to remove duplicate elements in a tuple or a list is a very common use case in Python.

You might also be interested in –


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.


Author

  • Piyush Raj

    Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

Scroll to Top