I am looking for an python inbuilt function (or mechanism) to segment a list into required segment lengths (without mutating the input list). Here is the code I already have:
>>> def split_list(list, seg_length):
... inlist = list[:]
... outlist = []
...
... while inlist:
... outlist.append(inlist[0:seg_length])
... inlist[0:seg_length] = []
...
... return outlist
...
>>> alist = range(10)
>>> split_list(alist, 3)
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
How do you need to use the output? If you only need to iterate over it, you are better off creating an iterable, one that yields your groups:
Usage example:
This uses far less memory than trying to construct the whole list in memory at once, if you are only looping over the result, because it only constructs one subset at a time:
You can use list comprehension:
not the same output, I still think the grouper function is helpful:
for Python2.4 and 2.5 that does not have izip_longest:
some demo code and output:
output: [(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, None, None)]