Python | Merging duplicates to list of list

Sometimes, we need to perform the conventional task of grouping some like elements to a separate list and thus forming a list of list. This can also helps in counting and also get the sorted order of elements. Let’s discuss certain ways in which this can be done.

Method #1 : Using collections.Counter()
This particular function can prove to be quite useful to perform this particular task as it counts the frequency of elements in list and then we can pair them using the list comprehension.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate
# grouping like elements as list 
# using collections.Counter()
import collections
  
# initializing list 
test_list = [1, 3, 4, 2, 1, 3, 4, 2, 3, 4, 1]
  
# printing original list 
print("The original list : " + str(test_list))
  
# using collections.Counter()
# grouping like elements as list 
temp = collections.Counter(test_list)
res = [[i] * j for i, j in temp.items()]
  
# print result
print("The elements after grouping are : " + str(res))

chevron_right


Output :



The original list : [1, 3, 4, 2, 1, 3, 4, 2, 3, 4, 1]
The elements after grouping are : [[1, 1, 1], [2, 2], [3, 3, 3], [4, 4, 4]]

 

Method #2 : Using itertools.groupby()
This problem can easily solved by traditional groupby functionality that is offered by Python via groupby function, which groups the like elements as suggested by name.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate
# grouping like elements as list 
# using itertools.groupby()
import itertools
  
# initializing list 
test_list = [1, 3, 4, 2, 1, 3, 4, 2, 3, 4, 1]
  
# printing original list 
print("The original list : " + str(test_list))
  
# using itertools.groupby()
# grouping like elements as list 
res = [list(i) for j, i in itertools.groupby(sorted(test_list))]
  
# print result
print("The elements after grouping are : " + str(res))

chevron_right


Output :

The original list : [1, 3, 4, 2, 1, 3, 4, 2, 3, 4, 1]
The elements after grouping are : [[1, 1, 1], [2, 2], [3, 3, 3], [4, 4, 4]]


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.