confused about adding elements to a list with list.append(otherlist)

Hans Nowak hnowak at cuci.nl
Mon Aug 13 13:46:29 CEST 2001


>===== Original Message From tist.verdonck at mailandnews.com (Tist Verdonck) 
=====
>I got this problem where I have an empty list and I want to fill it up
>with other lists using a for-iteration:
>
>list = []
>data = ['ab','cd','de','ef','gh']
>z = len(data)
>for x in range(z):
>    list.append(data)
>    data.append('IJ')

list.append(data) adds a reference to data to the list. You end up with a list 
of references to the same object (data); that data changed during the loop is 
irrelevant in this situation.

Use list.append(data[:]) instead and the code will do what you intended (this 
will add a copy of data to the list).

>I think it must have something to do with me having problems with
>python's use of variables (not copying them but making references to them)

Yes, Python doesn't implicitly copy objects. In a language like C,

  int a, b = 42;
  a = b;

copies the value of b to a, but in Python

  b = 42
  a = b

a binding is created (b referring to an integer object with value 42), then a 
refers to that same object. Since integers are immutable, their behavior is 
unsurprising, because

  a = 28

will not change the value of b, just like "a = 28;" in C would not change the 
value of b.

Mutable objects behave the same way, really:

  b = [1, 2, 3]
  a = b

Now a and b refer to the same object, a list. And

  a = [4, 5]

does not change the value of b; it simply binds a to a new list with value 
[4,5]. Problems only occur in situations like

  b = [1, 2, 3]
  a = b
  a.append(4)

when people don't realize that mutating a also affects b, because they're the 
same object.

HTH,

--Hans Nowak





More information about the Python-list mailing list