Remove duplicate tuples from list of tuples in Python

PythonServer Side ProgrammingProgramming

When it is required to remove duplicate tuples from a list of tuples, the loop, the 'any' method and the enumerate method can be used.

The 'any' method checks to see if any value in the iterable is True, i.e atleast one single value is True. If yes, it returns 'True', else returns 'False'

A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on).

A list of tuple basically contains tuples enclosed in a list.

The enumerate method adds a counter to the given iterable, and returns it.

Below is a demonstration for the same −

Example

Live Demo

def delete_duplicate(my_lst):  
   return [[a, b] for i, [a, b] in enumerate(my_lst)
   if not any(c == b for _, c in my_lst[:i])]
     
my_list = [(23, 45), (25, 17), (35, 67), (25, 17)]

print("The list of tuples is")
print(my_list)
print("The function to remove duplicates is called")
print(delete_duplicate(my_list))

Output

The list of tuples is
[(23, 45), (25, 17), (35, 67), (25, 17)]
The function to remove duplicates is called
[[23, 45], [25, 17], [35, 67]]

Explanation

  • A method named 'delete_duplicate' is defined that takes a list of tuples as parameter.
  • It enumerates through the list of tuples and uses the 'any' method to see if the list contains atleast a single true value.
  • It returns the same as output.
  • A list of tuple is defined and displayed on the console.
  • The method is called by passing this list of tuple.
  • This output is displayed on the console.
raja
Published on 12-Mar-2021 06:11:11
Advertisements