In this article, we will learn to Find all anagrams of strings in list Python with examples. This can be a single string or a list of strings by using two different methods Lambda and filter () and counter().
Find all anagrams of strings in list Python Environment and requirements
Here we will make use of the filter() function. The filter() method filters the given sequence with the help of a function that tests each element in the sequence to be true or not.
syntax:
filter(function, sequence)
Parameters:
- function: a function that tests if each element of a sequence is true or not.
- sequence: sequence which needs to be filtered, can be sets, lists, tuples, or containers of any iterators.
- Returns: returns an iterator that is already filtered
1. Lambda to find all anagrams of string in list Python
- In the first method, First import the counter class from collections package.
- Then we create a list of string and give a string.
- Then find and return the anagrams of the given string from the list using lambda and counter method().
from collections import Counter
texts = ["ohanim", "hanimo", "animoh", "nimoha","imohan","mohan"]
str = "mohani"
print("Orginal list of strings:")
print(texts)
print("\nMethod 1")
result = list(filter(lambda x: (Counter(str) == Counter(x)), texts))
print("\nAnagrams of 'mohani' in the above string: ")
print(result)
#print(Counter(str))
Output:
Orginal list of strings:
[‘ohanim’, ‘hanimo’, ‘animoh’, ‘nimoha’, ‘imohan’, ‘mohan’]
Anagrams of ‘mohani’ in the above string:
[‘ohanim’, ‘hanimo’, ‘animoh’, ‘nimoha’, ‘imohan’]
Counter({‘m’: 1, ‘o’: 1, ‘h’: 1, ‘a’: 1, ‘n’: 1, ‘i’: 1})
2. counter to find all anagrams of string in list Python
Counter():
In Python counter is a subclass of the dictionary class. To use the counter we will first import “from collections import Counter”.
We need to pass the list to the counter() function. It will return the dictionary with the count of each element.
How does it work explanation:
- In second method we create lambda function for checking the anagram in given list.
- Then append the output of lambda function using for loop and append() method.
- Then print it.
print("\nMethod 2")
from collections import Counter
texts = ["ohanim", "hanimo", "animoh", "nimoha","imohan","mohan"]
str = "mohani"
print("Orginal list of strings:")
print(texts)
lst=[]
s= lambda x : (Counter(str) == Counter(x))
for i in texts:
if s(i)==True:
lst.append(i)
print("\nAnagrams of 'mohani' in the above string: ")
print(lst)
Output:
Orginal list of strings:
[‘ohanim’, ‘hanimo’, ‘animoh’, ‘nimoha’, ‘imohan’, ‘mohan’]
Anagrams of ‘mohani’ in the above string:
[‘ohanim’, ‘hanimo’, ‘animoh’, ‘nimoha’, ‘imohan’]