On 5/8/2009 8:17 PM Ross said...
I have a really long list that I would like segmented into smaller
lists. Let's say I had a list a = [1,2,3,4,5,6,7,8,9,10,11,12] and I
wanted to split it into groups of 2 or groups of 3 or 4, etc. Is there
a way to do this without explicitly defining new lists?

>>> a = [1,2,3,4,5,6,7,8,9,10,11,12]
>>>
>>> for k in [2,3,4,5,6]:
...     print [ a[j:j+k] for j in range(0,len(a),k) ]
...
[[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12]]
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12]]
[[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12]]

The point is of course to use the form a[j:j+k] which doesn't create new lists.

Emile

--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to