[Tutor] Copying a mutable

Steven D'Aprano steve at pearwood.info
Wed Jun 8 13:37:05 CEST 2011


Válas Péter wrote:

> Being one of the purposes of Python to be a simple educational language, I
> want to make this simple to a beginner who does care. :-)
> Here is a piece of code, Python 3.1.2, a small game with a list and a tuple:
>>>> li=[3,4]
>>>> id(li)
> 13711200
>>>> la=li
>>>> id(la)
> 13711200


You can make it simpler by ignoring id() and using the `is` operator 
instead. `is` is equivalent to this function:

def my_is(a, b):
     return id(a) == id(b)

Of course you don't need to use that, instead do this:

 >>> a = [1, 2, 3]
 >>> b = a
 >>> a is b
True



> My question is: how would you explain the different behaviour of a list and
> a tuple for a beginner? 

Lists are mutable, which means you can change them in-place. The *= 
command changes the list in place:

 >>> a = [1, 2]
 >>> b = a
 >>> b *= 2
 >>> a is b
True
 >>> b
[1, 2, 1, 2]


Since you have changed the list object itself, both a and b see the same 
change. Naturally, since a and b are nothing but two different names for 
the same object.


But tuples are immutable, which means you *cannot* change then in-place. 
Since *= cannot change the tuple in-place, it has to create a new tuple 
and assign it to the name on the left hand side:

 >>> c = (1, 2)
 >>> d = c
 >>> c is d
True
 >>> d *= 2
 >>> d
(1, 2, 1, 2)


c remains a name for the first tuple, and d is now a name for the new, 
expanded tuple:

 >>> c
(1, 2)
 >>> c is d
False



[...]
> Just to precisely understand English words, because this is a foreign
> language for me. As far as I understand, assignment means giving a value to
> a variable which is the expression used by classical languages that have
> variables (such as Pascal or Basic). Python has no variables, since even the
> simpliest data is an object, but we still say assignment, because it is
> comfortable.
> In this sense, if I say, "assignment" is a subset of "binding", is it
> correct?


I don't think so. They are definitely related, though, assignment in the 
Pascal or C sense is *like* name binding in the Python or Java sense, 
but they are not strictly subset/superset of each other.

If one was a subset of the other, then you could write down every fact 
about name binding:

Name binding is:
1. blah blah blah...
2. ...
3. ...
999. ...

and then every fact about assignment:

Assignment is:
1. blah blah blah...
2. ...
3. ...
777. ...

and every fact about assignment would also be a fact about name binding. 
But that's not the case.



-- 
Steven


More information about the Tutor mailing list