Find Anagrams in List of Words in Python (2 Examples)
Hi! This short tutorial will show you how to detect anagrams in a list of words in the Python programming language.
Here is an overview:
Let’s jump into the Python code!
Create Demo List
Here, we will create the demo Python list of strings whose anagrams (scrambled words) we want to extract in this tutorial.
So, in your Python programming IDE, run the code below to create the demo list:
word_list = ["listen", "silent", "elbow", "below", "state", "taste"] print(word_list) # ['listen', 'silent', 'elbow', 'below', 'state', 'taste'] print(type(word_list)) # <class 'list'>
With the demo list created, we will now examine two ways to get anagrams in the list of words.
Example 1: Detect Anagrams in List of Words Using defaultdict() Function
In this first example, we will use the defaultdict() function from the built-in collections module to return the anagrams in the list of words:
from collections import defaultdict anagram_dict = defaultdict(list) for word in word_list: key = ''.join(sorted(word)) anagram_dict[key].append(word) anagram_groups = [group for group in anagram_dict.values() if len(group) > 1] print(anagram_groups) # [['listen', 'silent', 'tinsel'], ['banana', 'nabana']] print(type(anagram_groups)) # <class 'list'>
In the above example, anagram_dict
is created as a defaultdict
with a list as the default value. This allows us to easily append words to anagrams associated with a specific key.
We then iterate over each word in word_list
. For each word, we sort the characters to create a sorted key.
This key is used to access the list of anagrams in anagram_dict
. The word is then appended to the list of anagrams for that key.
After processing all the words, we filter anagram_dict
to retrieve only the anagram groups with more than one word. This is done by using a list comprehension and checking the length of each group.
Finally, the resulting anagram groups are printed.
Example 2: Detect Anagrams in List of Words Using itertools.groupby() Method
In this second example, we will use itertools groupby() method to collect the anagrams in the list:
import itertools sorted_words = sorted(word_list) anagram_groups = [] for _, group in itertools.groupby(sorted_words, key=lambda x: ''.join(sorted(x))): group = list(group) if len(group) > 1: anagram_groups.append(group) print(anagram_groups) # [['below', 'elbow'], ['listen', 'silent'], ['state', 'taste']] print(type(anagram_groups)) # <class 'list'>
Here, we first sort word_list
in alphabetical order, storing the result in sorted_words
.
Then, we create an empty list anagram_groups
to store the identified anagram groups. We then utilize the groupby()
method to group the sorted words based on their sorted form.
The sorting is achieved by applying the lambda function lambda
x
:
''.join(sorted(x))
as the key function.
Within the loop, for each unique key (which represents a sorted form), the group holds the iterator for the corresponding words.
This iterator is converted to a list and assigned back to the group. If the length of the group is greater than 1, indicating an anagram group, it is appended to anagram_groups
.
After iterating through all the groups, anagram_groups
contains the identified anagram groups.
Video, Further Resources & Summary
Do you need more explanations on how to find anagrams in a list of words in Python? Then you should have a look at the following YouTube video of the Statistics Globe YouTube channel.
In the video, we explain in some more detail how to find anagrams in a list of words in Python.
The YouTube video will be added soon.
Furthermore, I encourage you to check out other interesting Python list tutorials on Statistics Globe, starting with these ones:
- Find Index in List of Lists in Python (3 Examples)
- Lists in Python (13 Examples)
- Find Union of Two Lists in Python (3 Examples)
- Difference Between List & pandas DataFrame in Python
- Append to 2D List in Python (3 Examples)
- Introduction to Python Programming
This post has shown, using two examples, how to find anagrams in a list of words in Python. Your use case will determine which method to adopt.
I do hope you found this tutorial helpful! In case you have further questions, you may leave a comment below.
This page was created in collaboration with Ifeanyi Idiaye. You might check out Ifeanyi’s personal author page to read more about his academic background and the other articles he has written for the Statistics Globe website.
Statistics Globe Newsletter