Python | Get duplicate tuples from a list

Method # 1: Using a comprehension list + set () + count ()
The initial approach that can be taken is that we can iterate over each tuple and check its number in the list with count () , if it is greater than one we can add it to the list. To remove multiple padding, we can convert the result to a set using set () .

# Python3 code to demonstrate how it works
# Get duplicate tuples from the list
# Using comprehension list + set () + count ()

 
# initialize the list

test_list = [( 3 , 4 ), ( 4 , 5 ), ( 3 , 4 ) , 

( 3 , 4 ), ( 4 , 5 ), ( 6 , 7 )]

 
# print original list

print ( "The original list:" + str (test_list))

 
# Get duplicate tuples from the list
# Using comprehension list + set () + count ()

res = list ( set ([ele for ele in test_list

if test_list.count (ele) & gt;  1 ]))

 
# print result

print ( "All the duplicates from list are:" + str (res))

Exit:

 The original list: [(3, 4), (4, 5), (3, 4), (3, 4), (4, 5), (6, 7) ] All the duplicates from list are: [(4, 5), (3, 4)] 

Method # 2: Using Counter () + items () + list comprehension
A combination of the above functions can also be used to accomplish this specific task. In this case, we just get the count of each occurrence of the element, using Counter () as a dictionary, and then retrieve all those with a value greater than 1.

# Python3 code to demonstrate how it works
# Get duplicate tuples from the list
# Usage list comprehension + Counter () + items ()

from collections import Counter

 
# initialize the list

test_list = [( 3 , 4 ), ( 4 , 5 ), ( 3 , 4 ), 

( 3 , 4 ), ( 4 , 5 ), ( 6 , 7 )]

 
# print original list

print ( "The original list:" + str (test_list))

  
# Get duplicate tuples from the list
# Using a list comprehension + Counter () + items ()

res = [ele for ele, count in Counter (test_list) .items ()

if count & gt;  1 ]

 
# print result

print ( "All the duplicates from list are:" + str (res))

Output:

 The original list: [(3, 4), (4, 5), (3, 4), (3, 4), (4, 5), (6, 7)] All the duplicates from list are: [(4, 5), (3, 4)]