Skip to content Skip to sidebar Skip to footer

Slicing A List Into A List Of Sub-lists

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: in

Solution 1:

[input[i:i+n] for i inrange(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.

Solution 2:

The documentation of the itertools module contains the following recipe:

import itertools

defgrouper(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)]

Solution 3:

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.

Solution 4:

I like SilentGhost's solution.

My solution uses functional programming in python:

group = lambda t, n: zip(*[t[i::n] for i inrange(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.

Post a Comment for "Slicing A List Into A List Of Sub-lists"