Python | Remove duplicate tuples from list of tuples
Given a list of tuples, Write a Python program to remove all the duplicated tuples from the given list.
Examples:
Input : [(1, 2), (5, 7), (3, 6), (1, 2)]
Output : [(1, 2), (5, 7), (3, 6)]
Input : [('a', 'z'), ('a', 'x'), ('z', 'x'), ('a', 'x'), ('z', 'x')]
Output : [('a', 'z'), ('a', 'x'), ('z', 'x')]
Method #1 : List comprehension
This is a naive approach to use list comprehension. Here, we use two for loops and set data structure to cancel out all the duplicates.
# Python3 program to remove duplicate # tuples from list of tuples def removeDuplicates(lst): return [t for t in (set(tuple(i) for i in lst))] # Driver code lst = [(1, 2), (5, 7), (3, 6), (1, 2)] print(removeDuplicates(lst)) |
[(1, 2), (5, 7), (3, 6)]
Method #2 : List comprehension (Efficient approach)
This method is efficient as compared to the above method, here we use a single for loop within list comprehension and then convert it to set to remove duplicates and then again convert it to list.
# Python3 program to remove duplicate # tuples from list of tuples def removeDuplicates(lst): return list(set([i for i in lst])) # Driver code lst = [(1, 2), (5, 7), (3, 6), (1, 2)] print(removeDuplicates(lst)) |
[(1, 2), (5, 7), (3, 6)]
Method #3 : Python enumerate() method
# Python3 program to remove duplicate # tuples from list of tuples def removeDuplicates(lst): return [[a, b] for i, [a, b] in enumerate(lst) if not any(c == b for _, c in lst[:i])] # Driver code lst = [(1, 2), (5, 7), (3, 6), (1, 2)] print(removeDuplicates(lst)) |
[[1, 2], [5, 7], [3, 6]]
Recommended Posts:
- Python | Remove tuples having duplicate first value from given list of tuples
- Python | Remove tuples from list of tuples if greater than n
- Python | Find the tuples containing the given element from a list of tuples
- Python | Count tuples occurrence in list of tuples
- Python | Combining tuples in list of tuples
- Python | Remove empty tuples from a list
- Python | Remove all strings from a list of tuples
- Python | Remove tuple from list of tuples if not containing any character
- Python | Remove matching tuples
- Python | Min and Max value in list of tuples
- Python | Group tuples in list with same first value
- Python | Unzip a list of tuples
- Python program to create a list of tuples from given list having number and its cube in each tuple
- Python | Reverse each tuple in a list of tuples
- Python | Finding frequency in list of tuples
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : ManasChhabra2



