slice iterator?

Scott David Daniels Scott.Daniels at Acm.Org
Sat May 9 06:49:43 CEST 2009


Ross 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:
> ... Ideally, my outcome would be
> [1,2,3]
> [4,5,6]
> [7,8,9]
> [10,11,12]

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

--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list