Let's say I have a list of arbitrary length, L:
L = list(range(1000))
What is the best way to split that list into groups of n
? This is the best structure that I have been able to come up with, and for some reason it does not feel like it is the best way of accomplishing the task:
n = 25
for i in range(0, len(L), n):
chunk = L[i:i+25]
Is there a built-in to do this I'm missing?
Edit: Early answers are reworking my for loop into a listcomp, which is not the idea; you're basically giving me my exact answer back in a different form. I'm seeing if there's an alternate means to accomplish this, like a hypothetical .split
on lists or something. I also do use this as a generator in some code that I wrote last night:
def split_list(L, n):
assert type(L) is list, "L is not a list"
for i in range(0, len(L), n):
yield L[i:i+n]