pythonlistsegments

Segment a list in Python


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

Solution

  • You can use list comprehension:

    >>> seg_length = 3
    >>> a = range(10)
    >>> [a[x:x+seg_length] for x in range(0,len(a),seg_length)]
    [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]