[Tutor] Sequential assignment to list subscripts

Magnus Lycka magnus@thinkware.se
Sun Nov 3 07:21:08 2002


At 22:41 2002-11-02 -0800, John Abbe wrote:
>Great. Can someone explain...
>
>>>>  a=b=[0]
>>>>  a
>[0]
>>>>  b
>[0]
>>>>  a[0], b[0] = 7, 8
>>>>  a
>[8]
>>>>  b
>[8]
>
>...why a[0] isn't equal to 7  ?!?

First of all: You can see a variable as a reference to an object,
or if you prefer, one of perhaps many names for an object. Variables
are typeless in python, and can be changed into referring to some
new object.

Objects on the other hand, are typed, and have all sorts of limitation
to their behaviour. Some objects are mutable, i.e. they can be modified
after creation, others are immuable. For instance, lists are mutable
and strings and integers are mutable.

 >>> a = [1,2,3]
 >>> a
[1, 2, 3]
 >>> a[1] = 'X'
 >>> a
[1, 'X', 3]
 >>> a = "123"
 >>> a[1] = 'X'
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
TypeError: object doesn't support item assignment

If you type
a = b = 7

it will be the same thing as

b = 7 # Let the variable 'b' refer to the integer object 7
a = b # Let the variable 'a' refer to the same object as
       # variable 'b' refers to

Both a and b will refer to the integer object 7 until
they are reassigned as in

b = "Hello"

Now a still points to the object 7, since that's where
it's been pointing since "a = b" above. a, on the other
hand, now points to the string object "Hello".

If you write "a = b = [0]" you are telling Python to:
1. Create a list object.
2. Let the first position in the list object refer to
    the integer object 0.
3. Let the variable b refer to this list object.
4. Let the variable a also refer to this list object.

If you would type

b = something_else, a and b would no longer point to
something else, but until you reassign a or b, they
will always point to the same object, this list.

As we said above, lists are mutable.

"a[0] = 5" does NOT reassign a. It reassigns position
0 of the list that a refers to. This is the same list
as b refers to. Thus the followint three lines of code
are equivalent:

a[0], b[0] = 5, 6
a[0], a[0] = 5, 6
b[0], b[0] = 5, 6

They both mean: First refer position 0 in our list to the
integer 5, and then to the integer 6...


-- 
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/  mailto:magnus@thinkware.se