Initializing a list with copies
Ralf Juengling
juenglin at informatik.uni-freiburg.de
Tue Apr 30 08:17:28 EDT 2002
billdozier at hotmail.com (Bill Dozier) writes:
> Ralf Juengling <juenglin at informatik.uni-freiburg.de> wrote in message news:<xduy9fa4z2x.fsf at leto.informatik.uni-freiburg.de>...
>
>
>
> This looks like the old "mutable initializer" thingie.
>
yeah probably old traps, newbies are falling into in any season.
> > >>> l = [[] for i in range(n)]
>
> > Can this be done more elegant?
> "[[] for i in range(n)]" looks fine to me.
>
> > By some expression that was similar to '[[]]*n' ?
> Do you mean, "with few characters to type?" That's not the same as
> "with more elegance."
That's admittedly a bit finical, but I don't like to have to create a
temporary list to create the list l. That's why it looks unelegant to
me. (Okay, I could use 'xrange' instead of 'range'...)
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?
Ralf
More information about the Python-list
mailing list