Breaking Python list into set-length list of lists

John Machin sjmachin at lexicon.net
Thu Feb 12 09:53:06 CET 2009


On Feb 12, 6:46 pm, Gerard Flanagan <grflana... at gmail.com> wrote:
> Jason wrote:
> > Hey everyone--
>
> > I'm pretty new to Python, & I need to do something that's incredibly
> > simple, but combing my Python Cookbook & googling hasn't helped me out
> > too much yet, and my brain is very, very tired & flaccid @ the
> > moment....
>
> > I have a list of objects, simply called "list".  I need to break it
> > into an array (list of lists) wherein each sublist is the length of
> > the variable "items_per_page".  So array[0] would go from array[0][0]
> > to array[0][items_per_page], then bump up to array[1][0] - array[1]
> > [items_per_page], until all the items in the original list were
> > accounted for.
>
> If you need to pad the last item:
>
> def chunk( seq, size, pad=None ):
>      '''
>      Slice a list into consecutive disjoint 'chunks' of
>      length equal to size. The last chunk is padded if necessary.
>
>      >>> list(chunk(range(1,10),3))
>      [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>      >>> list(chunk(range(1,9),3))
>      [[1, 2, 3], [4, 5, 6], [7, 8, None]]
>      >>> list(chunk(range(1,8),3))
>      [[1, 2, 3], [4, 5, 6], [7, None, None]]
>      >>> list(chunk(range(1,10),1))
>      [[1], [2], [3], [4], [5], [6], [7], [8], [9]]
>      >>> list(chunk(range(1,10),9))
>      [[1, 2, 3, 4, 5, 6, 7, 8, 9]]
>      >>> for X in chunk([],3): print X
>      >>>
>      '''
>      n = len(seq)
>      mod = n % size
>      for i in xrange(0, n-mod, size):
>          yield seq[i:i+size]
>      if mod:
>          padding = [pad] * (size-mod)
>          yield seq[-mod:] + padding
>
> If you search the list archive, there is surely an example which will do
> the same for an arbitrary iterable (in general, you can't assume that
> `len(seq)` will work for an iterable that is not a list, set or tuple).
> But if you are just starting with Python, don't worry about this.

Aren't you making it out to be more mysterious than it needs to be?

Let's show the guy just a teensy bit of Python 102:

| >>> import string; data = string.ascii_lowercase
| >>> page_size = 6
| >>> pages = []
| >>> index = 0
| >>> for item in data:
| ...    if not index:
| ...       pages.append([])
| ...       shelve_it = pages[-1].append
| ...    index = (index + 1) % page_size
| ...    shelve_it(item)
| ...
| >>> pages
| [['a', 'b', 'c', 'd', 'e', 'f'], ['g', 'h', 'i', 'j', 'k', 'l'],
['m', 'n', 'o', 'p', 'q', 'r'], ['s', 't', 'u', 'v', 'w', 'x'], ['y',
'z']]
| >>>



More information about the Python-list mailing list