Python Program to Group Strings by K length Using Suffix

When it is required to group strings by K length using a suffix, a simple iteration and the 'try' and 'except' blocks are used. This technique extracts the last K characters from each string and groups strings with the same suffix together.

Example

Below is a demonstration of the same ?

my_list = ['peek', "leak", 'creek', "weak", "good", 'week', "wood", "sneek"]

print("The list is :")
print(my_list)

K = 3

print("The value of K is")
print(K)

my_result = {}

for element in my_list:
   suff = element[-K : ]
   try:
      my_result[suff].append(element)
   except:
      my_result[suff] = [element]

print("The resultant list is :")
print(my_result)

Output

The list is :
['peek', 'leak', 'creek', 'weak', 'good', 'week', 'wood', 'sneek']
The value of K is
3
The resultant list is :
{'eek': ['peek', 'creek', 'week', 'sneek'], 'eak': ['leak', 'weak'], 'ood': ['good', 'wood']}

Using defaultdict Alternative

A cleaner approach uses `defaultdict` from the collections module ?

from collections import defaultdict

my_list = ['peek', 'leak', 'creek', 'weak', 'good', 'week', 'wood', 'sneek']
K = 3

my_result = defaultdict(list)

for element in my_list:
    suffix = element[-K:]
    my_result[suffix].append(element)

print("The grouped strings are:")
for suffix, words in my_result.items():
    print(f"'{suffix}': {words}")
The grouped strings are:
'eek': ['peek', 'creek', 'week', 'sneek']
'eak': ['leak', 'weak']
'ood': ['good', 'wood']

How It Works

  • A list of strings is defined and displayed on the console.

  • The value of 'K' is defined to specify suffix length.

  • An empty dictionary is defined to store grouped results.

  • The list is iterated over to extract each string's suffix.

  • The suffix is extracted using slice notation `element[-K:]`.

  • The 'try' block attempts to append the element to an existing suffix group.

  • The 'except' block creates a new group if the suffix doesn't exist yet.

  • The final dictionary groups strings by their common suffixes.

Conclusion

Grouping strings by suffix involves extracting the last K characters and using a dictionary to collect strings with matching suffixes. The `defaultdict` approach provides cleaner code without try-except blocks.

Updated on: 2026-03-26T02:48:19+05:30

304 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements