Python | Remove tuples having duplicate first value from given list of tuples
Last Updated :
28 Mar, 2023
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:
- Initialize a list of tuples named "Input" with some values.
- Create an empty set named "seen".
- 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.
- 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.
- If the tuple passes the above condition, add it to a new list named "Output".
- Print the original input list of tuples.
- 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
OutputInitial 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)
OutputInitial 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 Tutorial | Learn Python Programming Language Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read