# Python | Program for counting duplicates in a list of tuples

Counters | Loops | Python Methods and Functions

Examples :

Input: [('a', 'e'), ('b', 'x' ), ('b', 'x'), ('a', 'e'), ('b', 'x')]
Output:
( 'a', 'e') - 2
('b', 'x') - 3

Input: [(0, 5), (6 , 9), (0, 8)]
Output: No Duplicates

Let's see how we can count the duplicates in a list of tuples.

Approach # 1: The Naive Approach

This approach uses two loops to iterate over the elements of the list and check if the first and second element of each element matches any other tuple.

` `

` Exit : Test Case 1: ('a',' e') - 2 ('b',' x') - 3 Test Case 2: No Duplicates Time complexity — O (n) 2 Approach # 2. Using the counter Counter — it is a container included in the collections module. It is an unordered collection that stores elements and their corresponding counts as a dictionary. # Python3 code to convert the tuple # to string def count (listOfTuple):     flag = False   # Add duplicate elements to list coll_list = []  coll_cnt = 0 for t in listOfTuple:   # To check if there is duplicate if t in coll_list:    flag = True continue   else : coll_cnt = 0 for b in listOfTuple: if b [ 0 ] = = t [ 0 ] and b [ 1 ] = = t [ 1 ]: coll_cnt = coll_cnt + 1   # Print quantity if duplicate element exists if (coll_cnt & gt;  1 ):    print (t, "-" , coll_cnt)   coll_list.append (t)   if flag = = False : print ( "No Duplicates" )   # Driver code print ( "Test Cas e 1: " ) listOfTuple = [( 'a' , 'e' ), ( ' b' , 'x' ), ( ' b' , 'x' ),  ( 'a' , 'e' ), ( ' b' , 'x' )]    count (listOfTuple)   print ( " Test Case 2: " ) listOfTuple = [( 0 , 5 ), ( 6 , 9 ), ( 0 , 8 )] count (listOfTuple) # Python3 code to transform a tuple # to line import collections   def count (listOfTuple):   flag = False val = collections.Counter (listOfTuple) uniqueList = list ( set (listOfTuple))   for i in uniqueList: if val [i ] & gt; = 2 : flag = True print (i, "-" , val [i])     < code class = "keyword"> if flag = = False : print ( "Duplicate doesn't exist" )   # Driver code listOfTuple = [( ' a' , 'e' ), ( 'b' , ' x' ), ( 'b' , ' x' ),  ( 'a' , ' e' ), ( 'b' , 'x' )]  count (listOfTuple) `

` ` Exit:

` ('b',' x' ) - 3 ('a',' e') - 2 `

Time complexity — O (n)

Approach # 3 Using a different dictate

You can create a dictionary, say ` count_map `, and keep the count each tuple as a value.

 ` # Python3 code to convert the tuple ` ` # into a string ` ` def ` ` count (listOfTuple): `   ` count_map ` ` = ` ` {} ` ` for ` ` i ` ` in ` ` listOfTuple: ` ` count_map [i] ` ` = ` count_map.get (i, ` 0 ` `) ` ` + ` ` 1 ` ` print ` ` (count_map) `   ` # Driver code ` ` print ` ` (` ` "Test Case 1: "` `) ` ` listOfTuple ` ` = ` ` [(` ` 'a' ` `, ` `' e' ` `), (` ` 'b' ` `, ` ` 'x' ` `), (` `' b' ` `, ` ` 'x' ` `), `   ` (` ` 'a' ` `, ` ` 'e' ` `), (` `' b' ` `, ` ` 'x' ` `)] `   ` count (listOfTuple) `

Exit :

` Test Case 1: {('a',' e'): 2, ('b',' x'): 3 } `

Time complexity — O (n)