List sequential initialization
Dave.Baum at motorola.com
Tue Jun 12 20:29:24 CEST 2007
In article <1181670619.086709.116730 at g37g2000prf.googlegroups.com>,
HMS Surprise <john at datavoiceint.com> wrote:
> I thought if I could do this:
> >>> a = b = ''
a and b refer to the same object (the empty string)
> >>> a = 'a'
You are assigning a new value to a - it now refers to the string 'a',
while b refers to the same thing it always has (the empty string)
> >>> a
> >>> b
> then this would behave similarly:
> >>> la = lb = 
la and lb refer to the same object, an empty list
> >>> la.append('a')
You are appending 'a' to the list that la refers to.
> >>> la
> >>> lb
Since lb referred to the same list as la, when you modified the list via
la.append, those changes can also be seen via lb.
If instead of la.append('a'), you had done:
la = ['a']
Then it would have behaved similarly to the first example, and lb would
still refer to an empty list.
> I thought wrong! But don't know why.
For immutable objects (such as integers, strings, and tuples), the
distinction between pointing to the same object or identical copies
isn't important since you cannot modify the objects. However, when you
use mutable objects (such as lists) and modify them, then it is
important to understand when you are dealing with the same object and
when you are copying the object.
Assignment makes a name refer to an object. Multiple names can refer to
the same object (which is what a=b=c does). If you want to make a copy
of the object, you need to do so explicitly:
>>> a = [1, 2, 3]
>>> b = list(a)
[1, 2, 3, 4]
[1, 2, 3]
More information about the Python-list