Change language

# Python | Remove duplicate tuples from a list of tuples

|

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: Understanding list

This is a naive approach to using list comprehension. Here we use two loops for and set the data structure to eliminate all duplicates.

` `

` # Python3 program for removing duplicates # tuples from the 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)) `

` ` Exit:

` [(1, 2), (5, 7), (3, 6)] `

Method # 2: List Comprehension (Effective Approach)

This method is effective when compared to with the above method, here we use one for loop within a list comprehension and then convert it to a set to remove duplicates and then convert it back to a list again.

 ` # Python3 duplicate remover ` ` # tuples from a 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)) `

Exit :

` [(1, 2), (5, 7), (3, 6)] `

Method # 3: method enums Python ()

` `

` # Python3 duplicate remover # 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)) `

` ` Exit:

` [[1, 2], [5, 7], [3, 6]] `

## Shop

Learn programming in R: courses

\$

Best Python online courses for 2022

\$

Best laptop for Fortnite

\$

Best laptop for Excel

\$

Best laptop for Solidworks

\$

Best laptop for Roblox

\$

Best computer for crypto mining

\$

Best laptop for Sims 4

\$

Latest questions

NUMPYNUMPY

Common xlabel/ylabel for matplotlib subplots

NUMPYNUMPY

How to specify multiple return types using type-hints

NUMPYNUMPY

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

NUMPYNUMPY

glob exclude pattern

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

NUMPYNUMPY

Python CSV error: line contains NULL byte

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

## Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

How to specify multiple return types using type-hints

Printing words vertically in Python

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries