-1

I want to split elements of a length greater than n in a list and keep both parts of the split without nesting them. For example if I have a list:

['abc', 'abcde', 'abcd']

and wanted to split any item with a length greater than 2 I would want to turn it into

['ab', 'c', 'ab', 'cd', 'e', 'ab', 'cd']
Bob
  • 3
  • 1
  • 3
    This seems like a combination of https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks and https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-a-list-of-lists/952952 , both very popular duplicate targets. – Karl Knechtel May 21 '21 at 06:41

1 Answers1

0

This code will work:

ls = ['abc', 'abcde', 'abcd']
new_ls = []
for item in ls:
    new_ls.extend([item[i:i+2] for i in range(0, len(item), 2)])
print(new_ls)
# ['ab', 'c', 'ab', 'cd', 'e', 'ab', 'cd']

The code block in the for loop is your actual splitting code, which just asks python to create a list of items of length 2 (but it will still go to the end of your list).

Kraigolas
  • 5,121
  • 3
  • 12
  • 37