Q:

Python program to remove duplicate tuples irrespective of order

belongs to collection: Python Tuple Programs

0

Example:

tuple = ("python", "includehelp", 43, 54.23)

List is a sequence data type. It is mutable as its values in the list can be modified. It is a collection of ordered set of values enclosed in square brackets [].

Example:

list = [3 ,1,  5, 7]

List of tuples is a list whose each element is a tuple.

Example:

tupList = [("python", 7), ("learn" , 1), ("programming", 7), ("code" , 3)]

Removing duplicate tuples irrespective of order

To remove duplicates irrespective of order, we need to sort the tuples of the list and then check for duplicate values to remove them and then print the values.

Input:
tupList = [(3, 1), (5, 8), (1, 3), (4, 8), (2, 9)]

Output:
[(3, 1), (5, 8), (1, 3), (4, 8), (2, 9)]

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Method 1:

We will first sort each tuple of the list using the sorted() method and map() method. Then, we will use sets to remove duplicates. And then we will convert it back to the list.

Program:

# Program to remove duplicate tuples 

# Creating and printing the list of tuples
tupList = [(3, 1), (5, 8), (1, 3), (4, 8), (2, 9)]
print("Initial List of Tuples : " + str(tupList))

# Removing all duplicate tuples from the list
tupListWoDup = list(set(map(tuple, map(sorted, tupList))))

# Printing the list of tuples 
print("List of Tuples after removal of duplicates : " + str(tupListWoDup))

Output:

Initial List of Tuples : [(3, 1), (5, 8), (1, 3), (4, 8), (2, 9)]
List of Tuples after removal of duplicates : [(2, 9), (1, 3), (5, 8), (4, 8)]

Method 2:

Another method to remove duplicate tuples is using list comprehension with a combination of sorted() and set() methods.

We will sort the list using the sorted() method and then using the set() method to remove duplicates. Then convert it back to list.

Program:

# Program to remove duplicate tuples 

# Creating and printing the list of tuples
tupList = [(3, 1), (5, 8), (1, 3), (4, 8), (2, 9)]
print("Initial List of Tuples : " + str(tupList))

# Removing all duplicate tuples from the list
sortedTup = [tuple(sorted(val)) for val in tupList]
tupListWoDup = list(set(sortedTup))

# Printing the list of tuples 
print("List of Tuples after removal of duplicates : " + str(tupListWoDup))

Output:

Initial List of Tuples : [(3, 1), (5, 8), (1, 3), (4, 8), (2, 9)]
List of Tuples after removal of duplicates : [(2, 9), (1, 3), (5, 8), (4, 8)]

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Tuple Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to order tuples by list... >>
<< Python program to sort tuples by frequency of thei...