slice iterator?

John O'Hagan research at johnohagan.com
Fri May 8 23:48:48 EDT 2009


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:
>
> start = 0
> stop = 3
> for i in range(len(a)):
>     segment = a[start:stop]
>     print segment
>     start += stop
>     stop += stop

This doesn't work because you're looping over every element in your list 
(instead of every slice) and because you're incrementing the increment by 
using "stop" for two different things (endpoint and increment).

This seems to work:

>>> for i in range (len(a) / 3):
...     segment = a[3 * i:3 * (i + 1)]
...     print segment

Regards,

john



More information about the Python-list mailing list