slice iterator?

John O'Hagan research at johnohagan.com
Sat May 9 00:05:13 EDT 2009


On Sat, 9 May 2009, John O'Hagan wrote:
> On Sat, 9 May 2009, Ross wrote:
> > 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? If the above
> > problem were to be split into groups of 3, I've tried something like:
[..]
>
> This seems to work:
> >>> for i in range (len(a) / 3):
>
> ...     segment = a[3 * i:3 * (i + 1)]
> ...     print segment
[...]

But if len(a) is not divisible by the increment, that misses the last (short) 
slice, so using the step argument to range:

>>> for i in range (0, len(a), 3):
...     segment = a[i:i + 3]
...     print segment

is better. Or as a list comprehension:

[a[i:i + 3] for i in range (0, len(a), 3)]


HTH,

John



More information about the Python-list mailing list