Python | Group Anagrams from given list

Anagrams are the words that are formed by similar elements but the orders in which these characters occur differ. Sometimes, we may encounter a problem in which we need to group the anagrams and hence solution to above problem always helps. Let’s discuss certain ways in which this can be done.

Method #1 : Using defaultdict() + sorted() + values()

The combination of above functions can be used to get the solution of above problem. In this, we first get the anagrams grouped using defaultdict and use sorted function to get each anagram root value to group anagrams.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate
# Grouping Anagrams
# using defaultdict() + sorted() + values()
from collections import defaultdict
  
# initializing list
test_list = ['lump', 'eat''me''tea', 'em', 'plum']
  
# printing original list
print("The original list : " + str(test_list))
  
# using defaultdict() + sorted() + values()
# Grouping Anagrams
temp = defaultdict(list)
for ele in test_list:
    temp[str(sorted(ele))].append(ele)
res = list(temp.values())
  
# print result
print("The grouped Anagrams : " + str(res))

chevron_right


Output :

The original list : ['lump', 'eat', 'me', 'tea', 'em', 'plum']
The grouped Anagrams : [['me', 'em'], ['lump', 'plum'], ['eat', 'tea']]

 

Method #2 : Using list comprehension + sorted() + lambda + groupby()

The combination of above function can also be used to perform this particular task. The groupby function performs the necessary grouping together. The lambda function helps to group alike anagrams.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate
# Grouping Anagrams
# using list comprehension + sorted() + lambda + groupby()
from itertools import groupby
  
# initializing list
test_list = ['lump', 'eat''me''tea', 'em', 'plum']
  
# printing original list
print("The original list : " + str(test_list))
  
# using list comprehension + sorted() + lambda + groupby()
# Grouping Anagrams
temp = lambda test_list: sorted(test_list)
res = [list(val) for key, val in groupby(sorted(test_list, key = temp), temp)]
  
# print result
print("The grouped Anagrams : " + str(res))

chevron_right


Output :

The original list : ['lump', 'eat', 'me', 'tea', 'em', 'plum']
The grouped Anagrams : [['me', 'em'], ['lump', 'plum'], ['eat', 'tea']]


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.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.