Slicing A List Into Equal Groups in Python

There are several ways to do this, but I found out today that it’s possible to use itertools’ izip method to achieve the same effect as well, so I thought I would note it down here to reference later.

Basically, we want to take a list and group it into sublists that don’t go over a specific length. I am using this to partition lists into rows, to be used as a Django template tag. Here is how it works with izip:

>> from itertools import izip
 
>> l = range(10)
 
>> [s for s in izip(*[iter(l)] * n)] + [l[len(l) - (len(l) % n):]]
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]

izip ignores the rest of the list if it doesn’t break cleanly, that’s why there has to be an additional part there to add the remainder of the items. Apparently a new method called izip_longest was introduced in 2.6 that takes extra items into account as well.

It is also worth noting that some excellent partitioning filters can be found at Django snippets, this is mainly for fun!

Comments (3)