[Tutor] Copying list contents

alan.gauld@bt.com alan.gauld@bt.com
Tue, 30 Jul 2002 10:59:11 +0100


> > > Python treates the lists like objects
> > All python variables are references, regardless of the
> > object to which they point.

> Those this include variables of integer, strings and that kind of
> objects?

Yes, except those are immutable so you can't change them.
(The number 1 is always the number 1, you can assign a new number 
but you can't change the literal value... But the variable is still pointing

to a number object nonetheless)

Like so:

>>> a = 42     # create a number object with immutable value 42
>>> b = a      #  points to the same number object
>>> a = 27    #  can't change '42' so create a new number object value 27
>>> print a,b    # a is 27, b is 42
>>> a = [1,2,3]  # same a but now pointing at a list object
>>> b = a      # same b but now pointing at a's list (27 & 42 now get
garbage collected)
>>> a[0] = 42  # create a new number, value 42 and make the 1st element of
list point at it
>>> b        # b still points at a's list which now holds a new 1st element
[42, 2 ,3 ]
>>> b = a[:]   # b now has a copy of a's list
>>> a[0] = 27  # new number value 27(garbage collect 42), point at 27 from
list
>>> b      # b now unchanged
[42, 2 ,3 ]
>>> a     # but a is changed
[27, 2, 3]

Hopefully that helps,

Its actually slightly more complicated because for performance reasons
Python 
actually caches some low integer values, but the principle holds.
Everything is a reference, including the members of the list!

Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld