Alex Rivera | Logout

Segment a list in Python

Asked 2009-08-02T12:14:15.530
13

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]]
Edit
Report

1 Answer

3

not the same output, I still think the grouper function is helpful:

from itertools import izip_longest
def grouper(iterable, n, fillvalue=None):
    args = [iter(iterable)] * n
    return izip_longest(*args, fillvalue=fillvalue)

for Python2.4 and 2.5 that does not have izip_longest:

from itertools import izip, chain, repeat
def grouper(iterable, n, padvalue=None):
    return izip(*[chain(iterable, repeat(padvalue, n-1))]*n)

some demo code and output:

alist = range(10)
print list(grouper(alist, 3))

output: [(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, None, None)]

answered 2009-08-02T12:38:36.583

Your Answer