Skip to content

Write a Python program to check whether tuple is having duplicate items are not 

In this tutorial we will Write a Python program to check whether tuple is having duplicate items are not .

Steps to check whether tuple is having duplicate items are not 

If we only ant to check whether tuple is having duplicate items are not , the steps are as follows –

  • Convert the tuple to a set and store it in a new variable .
  • We know that tuple allows duplicate values but the set does not . So after converting to a set duplicate values in tuple will be vanished .
  • So length of tuple and length of set will be different
  • So If length of tuple and length of set is different then we can conclude that tuple is having duplicate item otherwise not .

Python program to check whether tuple is having duplicate items are not

# defining a function to check
# if a tuple has duplicate item or not
def has_duplicate(mytuple):
    # converting the tuple to set
    myset=set(mytuple)
    if len(mytuple)==len(myset):
        print("The tuple has no duplicate item")
    else:
        print("The tuple has duplicate item")
        
has_duplicate((1,2,3,4,5,3))
has_duplicate((1,2,3,4))
The tuple has duplicate item
The tuple has no duplicate item
  • In the above code first we have defined a function named has_duplicate to check whether a tuple is having duplicate items or not
  • Then we have called this function two times using various tuple . First time we have used a tuple which have duplicate items . Second time we have used a tuple which do not have duplicate items . From the output we can see the desired result .

But if we need to find out what is the duplicate items in a tuple then we need to follow the below steps-

Steps to find out duplicate items in a tuple

  • First we will create a empty dictionary .
  • Then we will iterate the tuple and add the items of the tuple as dictionary key and value of those key will be the count of those key in the tuple .
  • After that we will delete those key from the dictionary whose value is 1 .

Python program to find out duplicate items in a tuple

# defining a function to find out
# duplicate items in a tupke
def duplicate_items(mytuple):
    mydict={}
    for item in mytuple:
        if mytuple.count(item)>1:
            mydict[item]=mytuple.count(item)
    return mydict   

print(duplicate_items((1,2,3,4,5,5,3)))
{3: 2, 5: 2}
  • In the above code first we have defined a function named duplicate_items to find out the duplicate items in a tuple .
  • Then we have called this function with a tuple (1,2,3,4,5,5,3). From the output we can see that 3 and 5 is duplicate items in the tuple .

Thank you for reading this Article . If You enjoy it Please Share the article . If you want to say something Please Comment .

Leave a Reply