Breaking Python list into set-length list of lists

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Thu Feb 12 00:56:27 EST 2009


On Wed, 11 Feb 2009 20:58:28 -0800, Jason wrote:

> I have a list of objects, simply called "list".  

Generally speaking, that's not a good choice of names, because it over-
writes ("shadows") the built-in function 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.


This may not be the simplest or most efficient way of doing it, but it 
doesn't involve any advanced techniques other than slicing (which is 
pretty fundamental to Python).


>>> from string import lowercase  # just some random data
>>> list = list(lowercase)
>>> items_per_page = 5
>>> array = []
>>> num_sublists = len(list)//items_per_page
>>> if len(list) % items_per_page != 0:
...     num_sublists += 1
...
>>> for i in range(num_sublists):
...     array.append(list[i*items_per_page:(i+1)*items_per_page])
...
>>>
>>> from pprint import pprint
>>> pprint(array)
[['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']]
>>> 


There are other alternatives. Here's a more advanced technique:

>>> ipp = 7  # use a shorter name
>>> m, n = divmod(len(list), ipp)
>>> array = [list[i*ipp:(i+1)*ipp] for i in range(m+bool(n))]
>>> pprint(array)
[['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']]




-- 
Steven



More information about the Python-list mailing list