generating list of sub lists

Steve Holden steve at holdenweb.com
Sun Sep 16 11:56:38 EDT 2007


Rustom Mody wrote:
> 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?

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

seems a slightly neater way to meet the requirement.

regards
  steve
-- 
Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd           http://www.holdenweb.com
Skype: holdenweb      http://del.icio.us/steve.holden

Sorry, the dog ate my .sigline




More information about the Python-list mailing list