Reputation: 95
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
Upvotes: 1
Views: 1056
Reputation: 1
Try below this.
import string
li = list(string.ascii_lowercase);
liRes = []
for i in range(0,22):
liRes.append("".join(li[i:i+5]))
print(liRes)
Upvotes: 0
Reputation: 51162
It's more convenient to use a string than a list for this purpose, because you can slice a string to extract a substring. You can also import ascii_lowercase
from the string
module rather than writing it out yourself.
>>> from string import ascii_lowercase as alphabet
>>> [ alphabet[i:i+5] for i in range(len(alphabet) - 4) ]
['abcde', 'bcdef', 'cdefg', 'defgh', 'efghi', 'fghij', 'ghijk', 'hijkl',
'ijklm', 'jklmn', 'klmno', 'lmnop', 'mnopq', 'nopqr', 'opqrs', 'pqrst',
'qrstu', 'rstuv', 'stuvw', 'tuvwx', 'uvwxy', 'vwxyz']
Note that the range should go up to len(alphabet) - 4
(exclusive) so that the last substring has the full length of 5.
Upvotes: 0
Reputation: 26057
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)
Upvotes: 1
Reputation: 826
you are going too far in the list, your i will go all the way to i=26 and then you have no 27th, 28th, 29th or 30th letter
you could do something like:
combined_strings = ["".join([alphabet[i], alphabet[i+1], alphabet[i+2], alphabet[i+3], alphabet[i+4]]) for i in range(len(alphabet) - 4)]
Upvotes: 0