| home | about me | feed RSS feed

Every so often a given topic seems to strike a nerve with Stack Overflow users. One of the recent popular topics was the idiom:

L = [1,2,3,4,5,6]
chunk_size = 2

Which returns:


There were several related questions asked during a one- to two-day period regarding breaking a list into n chunks using this and other methods.
I posted an answer to one.
In that answer, I wanted to provide a visual representation of how the zip() method worked.

There must be a better way to visualize what's going on here, but this was what I came up with:

1,2,3,4,5,6    1,2,3,4,5,6  
^                ^
    ^                ^
        ^                ^

Edit: Tangentially related, below is a memory-efficient sequence chunker courtesy the Python community.
It uses itertools.izip_longest() to avoid issues associated with vanilla zip().

def chunker(some_iterable, chunk_size):
  import itertools as it
  yield it.izip_longest(*[iter(some_iterable)]*chunk_size, fillvalue=None)
created: 2010-02-11 | updated: 2011-08-03

on 2010-02-14 wife wrote:

That almost white background is a great idea, but please make it two shades darker, so the other people who don't know about it can also see it. Love ya.

on 2010-03-19 husband wrote:

Changed to #F0F0F0.
And I couldn't resist borrowing the top- and bottom-border style used on the Jinja2 website

on 2010-04-12 wife wrote:

Like the Jinja style :p

Comments are now closed for this post.