slice iterator?

ryles rylesny at gmail.com
Sat May 9 17:39:16 CEST 2009


On May 8, 11:17 pm, Ross <ross.j... at gmail.com> wrote:
> 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? 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
>
> Unfortunately start and stop don't increment using this code. Ideally,
> my outcome would be
> [1,2,3]
> [4,5,6]
> [7,8,9]
> [10,11,12]

There is also an iterator version here:
http://code.activestate.com/recipes/303279



More information about the Python-list mailing list