David (dblume) wrote,
David
dblume

Prepopulating lists with objects in Python

Dear self,

Never admit to the world you lost a couple of hours thinking that the following line created a list of objects.

    l = [Obj()] * n


It doesn't. It creates a list of references to one object.

What you meant to write was this:

    l = [Obj() for _ in range(n)]


You dummy.
Subscribe
  • Post a new comment

    Error

    Comments allowed for friends only

    Anonymous comments are disabled in this journal

    default userpic

    Your reply will be screened

    Your IP address will be recorded 

  • 0 comments