Python split list into chunks with repetitions

Viewed 50

I know that it is possible to do it like this:

test_list = ['1','2','3','4','5','6','7','8','9','10']

x = 3

final_list= lambda test_list, x: [test_list[i:i+x] for i in range(0, len(test_list), x)]

output=final_list(test_list, x)
output is: [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9'], ['10']]

but I have a bit different requirements. I should return this:

output is: [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9'], ['8','9', '10']]

In other words, I should allow repeating of numbers in the final chunk. Is there a simple way to do it?

1 Answers
lambda test_list, x: [test_list[min(i,len(test_list)-x):min(i+x,len(test_list))] for i in range(0, len(test_list), x)]

Would probably be more efficient to precalculate len(test_list) though

Pretty much: You said that you wanted the last element to not be the remaining elements, but the last x elements (right?), so that means that if there are less than x elements remaining (ie our index i is greater than or equal to length-x), we do not want to use i as starting index, we want to use length-x.

The second min I used (for the ending index) is not strictly necessary btw, just for cleanliness.

Related