I'm using Python 2.7 and I ran into the following situation:
I have a Polygon object that consists of N vertices stored in a list. I have abstracted out a function rand_xy()
that generates a random point to be a vertex, and I would like to create Polygon
objects with N random vertices.
I tried this:
vertices = [ rand_xy() ] * N
but it makes a list of N vertices that are all the same. And I guess it makes sense because the call to rand_xy() is evaluated first, and then it is duplicated N times.
I wish it would instead make the list by calling rand_xy()
N times. Is there any way to accomplish this (preferably in one line)?
I realized that the "obvious" way is to just do this:
vertices = []
for i in range( 0 , N ):
vertices.append( rand_xy() )
but my Polygon
constructor is
def __init__( self , vertices , color )
and I'd really like it if I could just set the default value of vertices
to be a random list of N points like this:
def __init__( self , vertices = [ rand_xy() ] * N , color = rand_rgb() )
This way, calling the Polygon
constructor with no arguments will give me a random new Polygon
. Or is there a better design choice for the constructor? Or can this just not be done in Python?
Thanks for the help!