Initializing a list with copies
Duncan Booth
duncan at NOSPAMrcp.co.uk
Tue Apr 30 09:40:05 EDT 2002
Ralf Juengling <juenglin at informatik.uni-freiburg.de> wrote in
news:xduu1pt1iuf.fsf at leto.informatik.uni-freiburg.de:
> Here's a proposal, that is 'more elegant' in my eyes. If the builtin
> 'list' type was an *iterable* factory function and we'd borrow the
> function 'take' from a more functional language, say
>
> def take(n, i):
> if not n:
> return []
> else:
> i = iter(i)
> return [i.next()] + take(n-1, i)
>
> then
>
> l = take(n, list)
>
> would do it.
>
> BTW: It is not easy to add __iter__ to list's meta-type, is it?
How about writing a generator to give you a list of any type:?
def listof(sometype=list):
while 1: yield sometype()
def take(n, i):
i = iter(i)
return [ i.next() for j in range(n) ]
take(6, listof(list))
take(99, listof(dict))
It occurs to me that it ought to be possible to produce a type
(pseudolist/lazylist?) that can be constructed from a sequence and has all
the methods of a list, but which only accesses the argument sequence when
it absolutely has to. e.g.:
lst1 = lazylist(listof())[:6]
lst2 = lazylist(file(name))[10:20]
--
Duncan Booth duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?
More information about the Python-list
mailing list