Python Merging duplicates to list of list (original) (raw)
Last Updated : 23 Jan, 2025
We are given a list we need to merge the duplicate to lists of list. **For example a list a=[1,2,2,3,4,4,4,5] we need to merge all the duplicates in lists so that the output should be [[2,2],[4,4,4]]. This can be done by using multiple functions like defaultdict from collections and Counter and various approaches with combinations of loop
Using collections.defaultdict
We can use defaultdict from collections can be used to group duplicates together efficiently.
Python `
from collections import defaultdict
a = [1, 2, 2, 3, 4, 4, 4, 5]
Initialize defaultdict with list as default factory
b = defaultdict(list)
Group duplicates together in lists
for item in a: b[item].append(item)
Get the lists of duplicates
c = [group for group in b.values() if len(group) > 1]
print("Merged List:", c)
`
Output
Merged List: [[2, 2], [4, 4, 4]]
**Explanation:
- Code uses a
defaultdict
with alist
as the default factory to group duplicate elements from the lista
. Each unique element froma
is added to the corresponding list in the dictionary. - After grouping, the code filters out groups with only one element, leaving only those lists with duplicates, which are then stored in
c
and printed as the merged list.
Using a Manual Approach
A more manual approach where we can iterate through the list and merge duplicates.
Python `
a = [1, 2, 2, 3, 4, 4, 4, 5]
Initialize an empty list to store merged lists
m = []
Iterate over the list and merge duplicates
while a: current = a[0] duplicates = [current]
# Find all occurrences of the current item
a = [item for item in a[1:] if item != current] # Remove the current item
m.append(duplicates + [item for item in a if item == current])
print("Merged List:", m)
`
Output
Merged List: [[1], [2], [3], [4], [5]]
**Explanation:
- Code iterates through the list
a
and extracts duplicates of the current element, adding them to aduplicates
list while filtering out occurrences of the current element froma
. - Each processed group of duplicates is appended to the
m
list, and this process repeats until all elements ina
have been processed.
Using collections.Counter
We can use Counter to count occurrences and then create lists of duplicates.
Python `
from collections import Counter
a = [1, 2, 2, 3, 4, 4, 4, 5]
Count occurrences of each element
c = Counter(a)
Create lists of duplicates
d = [[key] * c[key] for key in c if c[key] > 1]
print("Merged List:", d)
`
Output
Merged List: [[2, 2], [4, 4, 4]]
**Explanation:
Counter
from thecollections
module is used to count the occurrences of each element in the lista
.- Code then creates a list of lists (
d
), where each list contains duplicates of elements that occur more than once in the original list
Similar Reads
- Merge Two Lists Without Duplicates - Python We are given two lists containing elements and our task is to merge them into a single list while ensuring there are no duplicate values. For example: a = [1, 2, 3, 4] and b = [3, 4, 5, 6] then the merged list should be: [1, 2, 3, 4, 5, 6] Using set()set() function automatically removes duplicates m 2 min read
- Merge Two Lists into List of Tuples - Python The task of merging two lists into a list of tuples involves combining corresponding elements from both lists into paired tuples. For example, given two lists like a = [1, 2, 3] and b = ['a', 'b', 'c'], the goal is to merge them into a list of tuples, resulting in [(1, 'a'), (2, 'b'), (3, 'c')]. Usi 3 min read
- Python | Sort Flatten list of list The flattening of list of lists has been discussed earlier, but sometimes, in addition to flattening, it is also required to get the string in a sorted manner. Let's discuss certain ways in which this can be done. Method #1 : Using sorted() + list comprehension This idea is similar to flattening a l 7 min read
- List Product Excluding Duplicates - Python The task of finding the product of unique elements in a list involves identifying and multiplying only the distinct values, effectively excluding any duplicates. For example, if a = [1, 3, 5, 6, 3, 5, 6, 1], the unique elements would be {1, 3, 5, 6}, and the product of these values would be 90. Usin 3 min read
- Python - Convert List to List of dictionaries We are given a lists with key and value pair we need to convert the lists to List of dictionaries. For example we are given two list a=["name", "age", "city"] and b=[["Geeks", 25, "New York"], ["Geeks", 30, "Los Angeles"], ["Geeks", 22, "Chicago"]] we need to convert these keys and values list into 4 min read
- How to Find Duplicates in a List - Python Finding duplicates in a list is a common task in programming. In Python, there are several ways to do this. Let’s explore the efficient methods to find duplicates. Using a Set (Most Efficient for Large Lists)Set() method is used to set a track seen elements and helps to identify duplicates. [GFGTABS 2 min read
- Removing Duplicates of a List of Sets in Python Dealing with sets in Python allows for efficient handling of unique elements, but when working with a list of sets, you may encounter scenarios where duplicates need to be removed. In this article, we will see how we can remove duplicates of a list of sets in Python. Remove Duplicates of a List of S 2 min read
- Python | Remove duplicates from nested list The task of removing duplicates many times in the recent past, but sometimes when we deal with the complex data structure, in those cases we need different techniques to handle this type of problem. Let's discuss certain ways in which this task can be achieved. Method #1 : Using sorted() + set()Â Th 5 min read
- Python | Remove duplicates in Matrix While working with Python Matrix, we can face a problem in which we need to perform the removal of duplicates from Matrix. This problem can occur in Machine Learning domain because of extensive usage of matrices. Let's discuss certain way in which this task can be performed. Method : Using loop This 2 min read
- Python | Combine two lists by maintaining duplicates in first list Given two lists, the task is to combine two lists and removing duplicates, without removing duplicates in original list. Example: Input : list_1 = [11, 22, 22, 15] list_2 = [22, 15, 77, 9] Output : OutList = [11, 22, 22, 15, 77, 9] Code #1: using extend C/C++ Code # Python code to combine two lists 6 min read