In this tutorial, we will look at how to remove duplicates from a tuple in Python with the help of some examples.
How to remove duplicate elements from a tuple?
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.
Let’s look at some examples.
Remove duplicates from a tuple using a set
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)
(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.
- Create an empty result list (
result_ls) to store only the unique elements.
- Iterate through each element in the original tuple.
- For each element, check if its present in our result list, if it’s not present, add it to our result list.
- 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)
(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.