generating list of sub lists

Rustom Mody rustompmody at gmail.com
Sun Sep 16 05:09:58 EDT 2007


On 9/16/07, cesco <fd.calabrese at gmail.com> wrote:
> Hi,
>
> is there a one-liner to accomplish the following task?
> >From the list
> l = ['string1', 'string2', 'string3']
> generate the list of lists
> l = [['string1'], ['string1', 'string2'], ['string1', 'string2',
> 'string3']]
>
> Any help would be appreciated.
>
> Thanks
> Francesco
>>> l = [1,2,3,4,5]

>>> [l[:i]  for i in range(len(l))]
[[], [1], [1, 2], [1, 2, 3], [1, 2, 3, 4]]
>>>
well almost works except for the first empty list. [Are you sure you
dont want it?]

Corrected

>>> [l[:i+1] for i in range(len(l)-1)]
[[1], [1, 2], [1, 2, 3], [1, 2, 3, 4]]

Though I wonder if there is as neat a way as the first?



More information about the Python-list mailing list