Dynamically making lists?

Roman Suzi rnd at onego.ru
Mon Jun 4 06:35:22 EDT 2001


On Mon, 4 Jun 2001, Brian Lee wrote:

> Bill Witherspoon wrote:
> > 
> > Hi all,
> > 
> > If I have a list ->
> > 
> > L = ['one', 'two', 'three',......,'one thousand']
> > 
> > and I want to split this into several lists with (say) two elements
> > each ->
> > 
> > m = ['one', 'two']
> > n = ['three', 'four']
> > o = ['five', 'six'}
> > ......
> > zz = ['nine hundred ninety nine', 'one thousand']
> > 
> > How would I do this?  I don't know how many elements are in L before
> > I run the program.
> > 
> > It seems like I have to generate variable names on the fly?
> > Maybe there's something simple I'm missing here.
> > 
> > Any pointers would be appreciated.
> > 
> > TIA,
> > Bill.
> 
> How about to start from this code and edit for your own use.
> 
> for x in range(len(L) / 2):
>   tmp[x] = [L[x * 2], L[x * 2+ 1]]

The following solution creates list of lists:

>>> L = [1, 2, 3, 4, 5]
>>> [L[x:x+2] for x in range(0, len(L), 2) ]
[[1, 2], [3, 4], [5]]

Or for N:

>>> N = 3
>>> [L[x:x+N] for x in range(0, len(L), N) ]
[[1, 2, 3], [4, 5]]

Sincerely yours, Roman A.Suzi
-- 
 - Petrozavodsk - Karelia - Russia - mailto:rnd at onego.ru -
 





More information about the Python-list mailing list