how to build arbitrarily-sized lists in one fell swoop?
Remco Gerlich
scarblac-spamtrap at pino.selwerd.nl
Tue Jul 25 10:25:09 EDT 2000
Samuel Scarano wrote in comp.lang.python:
> There's a simple thing I want to do in python but I can't find a way that is
> obvious to the reader and efficient for the interpreter. I want to make a
> list with n copies of x.
>
> This is the way that's most obvious to me:
>
> l = []
> for i in range(n):
> l.append(x)
>
> But that looks awfully verbose for Python, and I'm sure there's a more
> efficient way.
>
> Then there's:
>
> l = map(lambda y: x, range(n))
>
> That's briefer, but it still involves a lot of function calls, and the
> wasteful construction of a range.
>
> So what's the right way?
l = [x]*n
Does what you do here. I don't know what kind of object x is, but note
that this doesn't make *copies* of x; if it's some instance, then all
elements of l will be a reference to the same old x. Same for your
methods.
--
Remco Gerlich, scarblac at pino.selwerd.nl
Hi! I'm a .sig virus! Join the fun and copy me into yours!
More information about the Python-list
mailing list