how to build arbitrarily-sized lists in one fell swoop?

Samuel Scarano srs25 at cornell.edu
Tue Jul 25 10:19:12 EDT 2000


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?

-- 
Samuel R. Scarano                        "Due to circumstances beyond my
Cornell University undergraduate         control, I am master of my fate
<srs25 at cornell.edu>                      and captain of my soul."
http://people.cornell.edu/pages/srs25/             -- Ashleigh Brilliant



More information about the Python-list mailing list