Python - Selective consecutive Suffix Join

When working with lists of strings, you may need to group consecutive elements that end with a specific suffix. This technique uses simple iteration with the endswith() method to join elements until a non-suffix element is found.

Example

Below is a demonstration of selective consecutive suffix join ?

my_list = ["Python-", "fun", "to-", "code"]

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

suffix = '-'
print("The suffix is :")
print(suffix)

result = []
temp = []
for element in my_list:
    temp.append(element)
    
    if not element.endswith(suffix):
        result.append(''.join(temp))
        temp = []

print("The result is :")
print(result)

The output of the above code is ?

The list is :
['Python-', 'fun', 'to-', 'code']
The suffix is :
-
The result is :
['Python-fun', 'to-code']

How It Works

The algorithm groups consecutive elements by:

  • Creating an empty result list to store final grouped strings
  • Using a temporary temp list to accumulate elements
  • Adding each element to temp as we iterate
  • When an element doesn't end with the suffix, joining all accumulated elements and adding to result
  • Resetting temp to start a new group

Alternative Implementation

Here's a more compact version using list comprehension and grouping logic ?

def consecutive_suffix_join(data, suffix):
    result = []
    temp = []
    
    for item in data:
        temp.append(item)
        if not item.endswith(suffix):
            result.append(''.join(temp))
            temp = []
    
    # Handle any remaining items
    if temp:
        result.append(''.join(temp))
    
    return result

words = ["hello-", "world", "test-", "data", "end-", "final"]
grouped = consecutive_suffix_join(words, '-')
print(grouped)
['hello-world', 'test-data', 'end-final']

Conclusion

Selective consecutive suffix join groups elements by accumulating them until a non-suffix element is found. This technique is useful for processing structured text data where certain delimiters indicate continuation.

Updated on: 2026-03-26T02:23:08+05:30

207 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements