Transforming a List of elements into a List of lists of elements

Jean-Michel Pichavant jeanmichel at sequans.com
Fri Jan 8 07:39:05 EST 2010


tiago almeida wrote:
> Hello all,
>
> I'd like to ask how you'd implement a function /f/ that transforms a 
> list of elements into a list of lists of elements by grouping 
> contiguous elements together.
> Examples:
>
> a=[1,2,3,4,5]
> print( f(a, 2) )   # -> [ [1, 2], [3, 4], [5] ]
> print( f(a, 3) )   # -> [ [1, 2, 3], [4, 5] ]
> print( f(a, 1) )   # -> [ [1], [2], [3], [4], [5] ]
>
>
> I have done a small function that does this using a while loop but 
> what I'm looking for is a more /pythonic/ way to do this. Maybe some 
> function in some standard Module does this and I don't know?
>
> Ps: I don't post the function here because I don't have it with me.
>
> Thanks a lot in advance!
> Tiago Almeida
> tiago.b.almeida at gmail.com <mailto:tiago.b.almeida at gmail.com>
>
using list comprehention 
(http://docs.python.org/tutorial/datastructures.html)
# note: poor naming
def func(l, slice):
    r = range(0, len(l), slice)
    result = [l[sl:sl+slice] for sl in r]
    print result

 >>> a=[1,2,3,4,5]
 >>> func(a,1) ; func(a,2) ; func(a,3)
[[1], [2], [3], [4], [5]]
[[1, 2], [3, 4], [5]]
[[1, 2, 3], [4, 5]]



I would add that I personally find list comprehension hard to read, so 
I'm not sure it is that pythonic. Your old school while loop could be 
less concise/elegant, but perfectly readable.

Jean-Michel



More information about the Python-list mailing list