Open In App

Python | Remove tuples having duplicate first value from given list of tuples

Last Updated : 28 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a list of tuples, the task is to remove all tuples having duplicate first values from the given list of tuples. 

Examples: 

Input:  [(12.121, 'Tuple1'), (12.121, 'Tuple2'), 
         (12.121, 'Tuple3'), (923232.2323, 'Tuple4')]
Output:  [(12.121, 'Tuple1'), (923232.2323, 'Tuple4')]
Input:  [('Tuple1', 121), ('Tuple2', 125), 
         ('Tuple1', 135), ('Tuple4', 478)]
Output:  [('Tuple1', 121), ('Tuple2', 125), ('Tuple4', 478)]

Below are some ways to achieve the above task. 

Method #1: Using Iteration 

Follow the below steps to implement the above idea:

  • First, a list of tuples named Input is initialized with four tuples. Each tuple has two elements: a floating-point number and a string.
  • An empty set named visited is created to store the unique first values of the tuples.
  • An empty list named Output is created to store the tuples with unique first values.
  • The program iterates over each tuple in the Input list using a for loop with two variables, a and b, to represent the first and second elements of each tuple, respectively.
  • Inside the loop, the program checks if the first value a is already in the set visited using the in keyword. If it is not in the set, the program adds it to the set using the add() method and appends the entire tuple (a, b) to the Output list using the append() method.
  • After all the tuples have been checked, the program prints the original list of tuples Input using the print() function with a string message. Then it prints the list of tuples with unique first values Output using the print() function with another string message.

Below is the implementation of the above approach:

Python3




# Python code to remove tuples having
# duplicate first value from given
# list of tuples
 
# Input list initialization
Input = [(12.121, 'Geeksforgeeks is best'),
         (19212.22, 'India is best'),
         (12.121, 'Cyware is best.'),
         (923232.2323, 'Jiit is best')]
 
# using set
visited = set()
 
# Output list initialization
Output = []
 
# Iteration
for a, b in Input:
    if not a in visited:
        visited.add(a)
        Output.append((a, b))
 
# Printing
print("Initial list of tuple is \n", Input)
print("List of tuple after removing duplicates:\n ", Output)


Output:

Initial list of tuple is [(12.121, ‘Geeksforgeeks is best’), (19212.22, ‘India is best’), (12.121, ‘Cyware is best.’), (923232.2323, ‘Jiit is best’)] List of tuple after removing duplicates: [(12.121, ‘Geeksforgeeks is best’), (19212.22, ‘India is best’), (923232.2323, ‘Jiit is best’)]

Time Complexity: O(n), where n is the number of tuples in the Input list.
Auxiliary Space: O(n), as we are using a set to keep track of visited first values and a list to store the output tuples.

Method #2: Using list comprehension 

Approach:

  1. Initialize a list of tuples named “Input” with some values.
  2. Create an empty set named “seen”.
  3. Use list comprehension to iterate over the tuples in the “Input” list and extract the first and second element of each tuple into variables “a” and “b”, respectively.
  4. Check if “a” is already in the “seen” set or not, and add it to the set if it is not already there. If “a” is already in the “seen” set, do not add the tuple to the output list.
  5. If the tuple passes the above condition, add it to a new list named “Output”.
  6. Print the original input list of tuples.
  7. Print the new list of tuples obtained after removing tuples with duplicate first elements.

Python3




# Python code to remove tuples having
# duplicate first value from given
# list of tuples
 
# Input list initialization
Input = [(12.121, 'Geeksforgeeks is best'),
         (19212.22, 'India is best'),
         (19212.22, 'Cyware is best.'),
         (923232.2323, 'Jiit is best')]
 
# Using set
seen = set()
 
# using list comprehension
Output = [(a, b) for a, b in Input
          if not (a in seen or seen.add(a))]
 
# Printing
print("Initial list of tuple is" \n, Input)
print("\nList of tuple after removing duplicates \n", Output)


Output:

Initial list of tuple is [(12.121, ‘Geeksforgeeks is best’), (19212.22, ‘India is best’), (19212.22, ‘Cyware is best.’), (923232.2323, ‘Jiit is best’)] List of tuple after removing duplicates [(12.121, ‘Geeksforgeeks is best’), (19212.22, ‘India is best’), (923232.2323, ‘Jiit is best’)]

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #3: Using itertools 

Python3




# Python code to remove tuples having
# duplicate first value from given
# list of tuples
 
import itertools
 
# Input list initialization
Input = [(12.121, 'Geeksforgeeks is best'),
         (19212.22, 'India is best'),
         (923232.2323, 'Cyware is best.'),
         (923232.2323, 'Jiit is best')]
 
# Using groupby
Output = ([next(b) for a, b in itertools.groupby(
    Input, lambda y: y[0])])
 
# Printing
print("Initial list of tuple is\n", Input)
print("\nList of tuple after removing duplicates\n", Output)


Output:

Initial list of tuple is [(12.121, ‘Geeksforgeeks is best’), (19212.22, ‘India is best’), (923232.2323, ‘Cyware is best.’), (923232.2323, ‘Jiit is best’)] List of tuple after removing duplicates [(12.121, ‘Geeksforgeeks is best’), (19212.22, ‘India is best’), (923232.2323, ‘Cyware is best.’)]

Time complexity: O(nlogn), where n is the length of the input list.
Auxiliary space: O(n), as the output list may have up to n elements (when there are no duplicates in the input list).

Method #4: Using OrderedDict This is the most elegant way to remove duplicates is using OrderedDict. 

Python3




# Python code to remove tuples having
# duplicate first value from given
# list of tuples
 
from collections import OrderedDict
 
# Input list initialization
Input = [(12.121, 'Geeksforgeeks is best'),
         (19212.22, 'India is best'),
         (19212.22, 'Cyware is best.'),
         (923232.2323, 'Jiit is best')]
 
# Using orderedDIct
Output = OrderedDict(Input).items()
 
# Printing
print("Initial list of tuple is\n", Input)
print("\nList of tuple after removing duplicates\n", Output)


Output:

Initial list of tuple is [(12.121, ‘Geeksforgeeks is best’), (19212.22, ‘India is best’), (19212.22, ‘Cyware is best.’), (923232.2323, ‘Jiit is best’)] List of tuple after removing duplicates odict_items([(12.121, ‘Geeksforgeeks is best’), (19212.22, ‘Cyware is best.’), (923232.2323, ‘Jiit is best’)])

Time complexity: O(n), where n is the number of tuples in the input list
Auxiliary space: O(n), where n is the number of tuples in the input list. 

Method#5: Using Recursive method

Python3




# Python code to remove tuples having
# duplicate first value from given
# list of tuples
 
 
def remove_duplicates(lst):
    # Base case: if list is empty or has only one element
    if len(lst) <= 1:
        return lst
       
    else:
        # Compare the first tuple with the rest of the tuples
        for i in range(1, len(lst)):
            if lst[0][0] == lst[i][0]:
                lst.pop(i)
                return [lst[0]] + remove_duplicates(lst[1:])
               
        # Recursive call
        return [lst[0]] + remove_duplicates(lst[1:])
 
 
# Input list initialization
Input = [(12.121, 'Geeksforgeeks is best'),
         (19212.22, 'India is best'),
         (19212.22, 'Cyware is best.'),
         (923232.2323, 'Jiit is best')]
 
# Removing duplicates
Output = remove_duplicates(Input)
 
# printing the original list
print('Initial list of tuple is\n', Input)
# Printing the output list
print("List of tuple after removing duplicates \n", Output)
 
# this code contributed by tvsk


Output

Initial list of tuple is
 [(12.121, 'Geeksforgeeks is best'), (19212.22, 'India is best'), (19212.22, 'Cyware is best.'), (923232.2323, 'Jiit is best')]
List of tuple after removing duplicates 
 [(12.121, 'Geeksforgeeks is best'), (19212.22, 'India is best'), (923232.2323, 'Jiit is best')]

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #6: Using dictionary

Use a dictionary to remove the tuples having a duplicate first value. In this approach, you can iterate through the list of tuples, and for each tuple, you can check if the first value is already present in the dictionary. If it is not present, you can add the key-value pair to the dictionary. If it is present, you can skip the tuple.

Python3




# Input list initialization
Input = [(12.121, 'Geeksforgeeks is best'),
         (19212.22, 'India is best'),
         (12.121, 'Cyware is best.'),
         (923232.2323, 'Jiit is best')]
 
# Dictionary to keep track of visited first values
visited = {}
 
# Output list initialization
Output = []
 
# Iterate through the list of tuples
for a, b in Input:
    # Check if the first value is already present in the dictionary
    if a not in visited:
        # If it is not present, add the key-value pair to the dictionary
        visited[a] = True
        # Append the tuple to the output list
        Output.append((a, b))
 
# Printing the results
print("Initial list of tuple is\n", Input)
print("List of tuple after removing duplicates:\n", Output)


Output

Initial list of tuple is
 [(12.121, 'Geeksforgeeks is best'), (19212.22, 'India is best'), (12.121, 'Cyware is best.'), (923232.2323, 'Jiit is best')]
List of tuple after removing duplicates:
 [(12.121, 'Geeksforgeeks is best'), (19212.22, 'India is best'), (923232.2323, 'Jiit is best')]

Time complexity: O(n), where n is the number of tuples in the input list. 
Auxiliary space: O(k), where k is the number of unique first values in the input list. 



Similar Reads

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
5 min read
Python | Remove tuples from list of tuples if greater than n
Given a list of a tuple, the task is to remove all the tuples from list, if it's greater than n (say 100). Let's discuss a few methods for the same. Method #1: Using lambda STEPS: Initialize a list of tuples: ini_tuple = [('b', 100), ('c', 200), ('c', 45), ('d', 876), ('e', 75)]Print the initial list: print("intial_list", str(ini_tuple))Define the
6 min read
Python | Get sum of tuples having same first value
Given a list of tuples, the task is to sum the tuples having the same first value. Examples: Input: [(1, 13), (2, 190), (3, 82), (1, 12)] Output: [(1, 25), (2, 190), (3, 82)]Input: [(1, 13), (1, 190), (3, 25), (1, 12)] Output: [(1, 215), (3, 25)] Let us discuss the different ways we can do this task. Method #1: Using map() C/C++ Code # Python code
6 min read
Python | Remove duplicate lists in tuples (Preserving Order)
Sometimes, while working with records, we can have a problem in which we need to remove duplicate records. This kind of problem is common in web development domain. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + set() In this method, we test for each list as it appears and add it to set so tha
7 min read
Python - Remove Duplicate subset Tuples
Sometimes, while working with Python tuples, we can have a problem in which we need to perform the removal of tuples, which are already present as subsets in other tuples. This kind of problem can be useful in data preprocessing. Let's discuss certain ways in which this task can be performed. Example: Input : test_list = [(6, 9, 17, 18), (15, 34, 5
6 min read
Python Program to Remove duplicate tuples irrespective of order
Given a list of binary tuples, the task is to write a Python program to remove all tuples that are duplicates irrespective of order, i.e delete if contains similar elements, irrespective of order. Input : test_list = [(4, 6), (1, 2), (9, 2), (2, 1), (5, 7), (6, 4), (9, 2)]Output : [(1, 2), (5, 7), (4, 6), (2, 9)]Explanation : (2, 1), (6, 4) are rem
6 min read
Python - Remove Tuples from the List having every element as None
Given a Tuple list, remove all tuples with all None values. Input : test_list = [(None, 2), (None, None), (3, 4), (12, 3), (None, )] Output : [(None, 2), (3, 4), (12, 3)] Explanation : All None tuples are removed.Input : test_list = [(None, None), (None, None), (3, 4), (12, 3), (None, )] Output : [(3, 4), (12, 3)] Explanation : All None tuples are
6 min read
Python program to create a list of tuples from given list having number and its cube in each tuple
Given a list of numbers of list, write a Python program to create a list of tuples having first element as the number and second element as the cube of the number. Example: Input: list = [1, 2, 3] Output: [(1, 1), (2, 8), (3, 27)] Input: list = [9, 5, 6] Output: [(9, 729), (5, 125), (6, 216)] Method #1 : Using pow() function.We can use list compreh
5 min read
Python | Find the tuples containing the given element from a list of tuples
Given a list of tuples, the task is to find all those tuples containing the given element, say n. Examples: Input: n = 11, list = [(11, 22), (33, 55), (55, 77), (11, 44)] Output: [(11, 22), (11, 44)] Input: n = 3, list = [(14, 3),(23, 41),(33, 62),(1, 3),(3, 3)] Output: [(14, 3), (1, 3), (3, 3)] There are multiple ways we can find the tuples contai
6 min read
Python - Filter all uppercase characters Tuples from given list of tuples
Given a Tuple list, filter tuples that contain all uppercase characters. Input : test_list = [("GFG", "IS", "BEST"), ("GFg", "AVERAGE"), ("GfG", ), ("Gfg", "CS")] Output : [('GFG', 'IS', 'BEST')] Explanation : Only 1 tuple has all uppercase Strings. Input : test_list = [("GFG", "iS", "BEST"), ("GFg", "AVERAGE"), ("GfG", ), ("Gfg", "CS")] Output : [
8 min read
Practice Tags :
three90RightbarBannerImg