remove duplicates from a tuple in python

Python – Remove Duplicates From Tuple

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

Tuples are immutable in Python. That is, they cannot be modified after creation. You can, however, use a set to create a new tuple with the duplicates removed from the original tuple.

remove duplicates from a tuple in python

Let’s look at some examples.

You can use a set to remove duplicates from a tuple in Python. First, create a set of unique elements from the tuple using the set() function and then use the tuple() function to create a new tuple from the resulting set.

# create a tuple
t = (1, 2, 3, 3, 4)
# remove duplicates
t = tuple(set(t))
print(t)

Output:

(1, 2, 3, 4)

You can see that the tuple now has only unique elements.

Note that we are not modifying the original tuple (tuples cannot be modified). Instead, we are creating a new tuple with only the unique elements and then assigning it to the variable storing the original tuple.

Alternatively, you can also use iteration to remove duplicates from a tuple. Again, here we are creating a new tuple with distinct elements as tuples cannot be modified. The following are the steps.

📚 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.

  1. Create an empty result list (result_ls) to store only the unique elements.
  2. Iterate through each element in the original tuple.
  3. For each element, check if its present in our result list, if it’s not present, add it to our result list.
  4. Use the tuple() function to convert the result list to a tuple.

Let’s look at an example.

# create a tuple
t = (1, 2, 3, 3, 4)
# remove duplicates
result_ls = []
for item in t:
    if item not in result_ls:
        result_ls.append(item)
t = tuple(result_ls)
print(t)

Output:

(1, 2, 3, 4)

We get the same result as above. The resulting tuple does not have any duplicates.

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