Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,924 questions

51,857 answers

573 users

How to convert a list of strings and group all the anagrams into sublists in Python

1 Answer

0 votes
from typing import List, Dict

# Groups a list of strings into sublists of anagrams.
def group_anagrams(words: List[str]) -> List[List[str]]:
    # Validate input
    if not isinstance(words, list):
        raise TypeError("Input must be a list of strings.")

    map: Dict[str, List[str]] = {}

    for word in words:
        if not isinstance(word, str):
            raise TypeError("All elements in the list must be strings.")

        # Sort characters
        sortword = ''.join(sorted(word))

        # Group words by their sorted key
        if sortword not in map:
            map[sortword] = []
        map[sortword].append(word)

    # Return grouped anagrams as a list of lists
    return list(map.values())


if __name__ == "__main__":
    try:
        lst = ["eat", "tea", "rop", "ate", "nat", "orp", "tan", "bat", "pro"]
        result = group_anagrams(lst)

        # Print result
        print("[")
        for group in result:
            print("  [ " + ", ".join(f"'{w}'" for w in group) + " ]")
        print("]")
    except Exception as error:
        print(error)


'''
run:

[
  [ 'eat', 'tea', 'ate' ],
  [ 'rop', 'orp', 'pro' ],
  [ 'nat', 'tan' ],
  [ 'bat' ]
]

'''

 



answered Nov 15, 2025 by avibootz
...