Skip to content

Comment on Python: copying a list the right way

Comments

I knew white space means a lot in Python (Disc: newbee and learning Python still!). Just found this, and thought someone out there might be able to throw some more light.

  Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32
  Type "copyright", "credits" or "license()" for more information.
  >>> a=[1,2,3]
  >>> b=a
  >>> b
  [1, 2, 3]
  >>> a=[1]
  >>> b
  [1, 2, 3]
  >>> id(a)
  18704984
  >>> id(b)
  18721728
  >>> c = [4, 5, 6]
  >>> d = c
  >>> id(c)
  10755928
  >>> id(d)
  10755928
  >>> print c, d
  [4, 5, 6] [4, 5, 6]
  >>> c = [7]
  >>> print c, d
  [7] [4, 5, 6]
  >>> e = c
  >>> c.append(8)
  >>> print c, d, e
  [7, 8] [4, 5, 6] [7, 8]
  >>>

c = [4,5,6] is creating a new list, and assigning it to c; not modifying the list that c pointed to. The '=' operator simply associates an object reference to a variable. Going d=c is copying the reference to an object from one variable to another.

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.