References vs copies w/ *x

Jeremy Hylton jeremy at cnri.reston.va.us
Fri Oct 1 12:13:30 EDT 1999


>>>>> "BZ" == Zamboo  <despamme.bstankie at eye.psych.umn.edu> writes:

  BZ> Hello, I have read through the Learning Python book and have
  BZ> found some peculiar behavior with the *x (repetition) command.
  BZ> Here is what I am doing and getting:

  >>> a=[1,2,3] 
  >>> b=[a[:]]*3 
  >>> b
  [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
  >>> b[0][2]=10 
  >>> b
  [[1, 2, 10], [1, 2, 10], [1, 2, 10]]

  BZ> Notice that if I change one of the elements in b, it changes all
  BZ> of the elements.  I assume that the repetition is also
  BZ> referencing a memory location, but how can I force the
  BZ> repetition command to make copies?

Your analysis is correct.  The second line of Python code makes a
single copy of a -- "a[:]", puts it inside a list -- "[a[:]]", and
then repeats the contents of that list three times -- "[a[:]] * 3".
So the copy is happening before the repition.  

As far as I know, there is no way to use * on a list and make it mean
copy.  You'll need to use a slightly more verbose, and thus slightly
easier to understand, construct.  For example:

b = []
for i in range(3):
    b.append(a[:])

Jeremy




More information about the Python-list mailing list