Best pattern/idiom

Peter Hansen peter at engcorp.com
Mon Aug 9 15:28:13 EDT 2004


Chris Connett wrote:

> I was wondering if there were a well known pattern/idiom for breaking a 
> sequence into a list of lists, each n elements long, e.g.
> 
> [0,1,2,3,4,5,6,7,8,9,10,11] -> [[0,1,2,3],[4,5,6,7],[8,9,10,11]]
> 
> This comes up reasonably often in my work, and every time I re-think 
> about it, and come up with
> [ lis[n:n+4] for n in range( 0, len( lis ), 4 ) ]
> which seems very kludgy to me, since it uses a range and len, 2 mentions 
> of the list identifier and 2 literal 4's (which is the size I want to 
> break into this time).
> 
> Is there a better way?

Found from a Peter Otten post via Google Groups (searching for
"islice list split"):

 >>> def chunks(s, size):
...   for i in range(0, len(s), size):
...     yield s[i:i+size]
 >>> s
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
 >>> list(chunks(s, 4))
[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]
 >>> list(chunks([], 4))
[]
 >>> list(chunks(s[:10], 4))
[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9]]

Of course, this uses range and len as well, and two mentions
of the identifier.  A function would have let you avoid the
duplicated literal 4, as this does also.

Now, define "better". ;-)  Some tasks have an inherent
complexity that can't be shrunk below a certain size...

-Peter



More information about the Python-list mailing list