Search code examples
pythonstringlistconcatenation

Is there a way to join every n elements of a list


Say I have a list of 26 elements, each a letter of the alphabet as below:

alphabets = ['a', 'b', ... , 'y', 'z']

My objective is to join every 5 elements iteratively, yielding:

combined_strings = ['abcde', 'bcdef', ... 'vwxyz']

I've tried:

combined_strings = []
for i, k in enumerate(alphabets):
    temp_string = k[i] + k[i+1] + k[i+2] + k[i+3] + k[i+4]
    combined_strings.append(temp_string)

but I am met with IndexError: List index out of range


Solution

  • You are using enumerate in wrong way. enumerate gives both index and the element at that index, so k[i] does not make any sense. Additionally, iterating over the full length causes IndexError as then you will be accessing elements at 27, 28, 29, 30 which are non-existent.

    You can correct your code to:

    combined_strings = []
    for i in range(len(alphabets)-4):
        temp_string = alphabets[i] + alphabets[i+1] + alphabets[i+2] + alphabets[i+3] + alphabets[i+4]
        combined_strings.append(temp_string)