Skip to Content

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.

  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 is a data scientist passionate about using data to understand things better and make informed decisions. In the past, he's worked as a Data Scientist for ZS and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.