Slicing a list into a list of sub-lists

Question:

What is the simplest and reasonably efficient way to slice a list into a list of the sliced sub-list sections for arbitrary length sub lists?

For example, if our source list is:

input = [1, 2, 3, 4, 5, 6, 7, 8, 9, ... ]

And our sub list length is 3 then we seek:

output = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], ... ]

Likewise if our sub list length is 4 then we seek:

output = [ [1, 2, 3, 4], [5, 6, 7, 8], ... ]
Asked By: James Austin

||

Answers:

[input[i:i+n] for i in range(0, len(input), n)]        # Use xrange in py2k

where n is the length of a chunk.

Since you don’t define what might happen to the final element of the new list when the number of elements in input is not divisible by n, I assumed that it’s of no importance: with this you’ll get last element equal 2 if n equal 7, for example.

Answered By: SilentGhost

The documentation of the itertools module contains the following recipe:

import itertools

def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return itertools.izip_longest(fillvalue=fillvalue, *args)

This function returns an iterator of tuples of the desired length:

>>> list(grouper(2, [1,2,3,4,5,6,7]))
[(1, 2), (3, 4), (5, 6), (7, None)]
Answered By: sth

I like SilentGhost’s solution.

My solution uses functional programming in python:

group = lambda t, n: zip(*[t[i::n] for i in range(n)])
group([1, 2, 3, 4], 2)

gives:

[(1, 2), (3, 4)]

This assumes that the input list size is divisible by the group size. If not, unpaired elements will not be included.

Answered By: MKTech

A really pythonic variant (python 3):

list(zip(*(iter([1,2,3,4,5,6,7,8,9]),)*3))

A list iterator is created and turned into a tuple with 3x the same iterator, then unpacked to zip and casted to list again. One value is pulled from each iterator by zip, but as there is just a single iterator object, the internal counter is increased globally for all three.

Answered By: CodeManX
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.