Breaking Python list into set-length list of lists
Mark Tolonen
metolone+gmane at gmail.com
Thu Feb 12 01:48:57 EST 2009
"Jason" <elgrandchignon at gmail.com> wrote in message
news:8158439d-faae-4889-a1cf-8d9fee112e9b at v39g2000yqm.googlegroups.com...
> 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.
>
> What would be the simplest way to do this in Python? And yes, I
> realize I should probably be taking Programming 101.....
>>> def splitlist(L,count):
... M=[]
... for i in xrange(0,len(L),count):
... M.append(L[i:i+count])
... return M
...
>>> L=range(18)
>>> splitlist(L,3)
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], [12, 13, 14], [15, 16, 17]]
>>> splitlist(L,4)
[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15], [16, 17]]
-Mark
More information about the Python-list
mailing list