[Tutor] Copying a mutable

Válas Péter sulinet at postafiok.hu
Wed Jun 8 08:30:39 CEST 2011


Walter and Dave, thank you for the useful and detailed answer, now I see it
better. I didn't write code, because once I realized I had spoiled
something, the mistake has no more importance except historical, the correct
solutions have importance.

2011. június 8. 4:19 Dave Angel írta, <davea at ieee.org>:

> Now, if an object is immutable, then the question of what happens when you
> change the object is nonsensical.  Since you can't change it, you don't
> really care if the two names are bound to same object, or just to two
> objects that happen to have the same value.
>

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
>>> li*=4
>>> li
[3, 4, 3, 4, 3, 4, 3, 4]
>>> la
[3, 4, 3, 4, 3, 4, 3, 4]
>>> id(li)
13711200
>>> tup=(3,4)
>>> id(tup)
13697392
>>> top=tup
>>> id(top)
13697392
>>> tup*=4
>>> tup
(3, 4, 3, 4, 3, 4, 3, 4)
>>> top
(3, 4)
>>> id(tup)
12956016
>>> id(top)
13697392
My question is: how would you explain the different behaviour of a list and
a tuple for a beginner? Formally we made the same intervention to these poor
guys, the list and the tuple, they look the same except parenthesis and
square bracket, but they reacted differently. Although tuples are immutable,
the beginner only sees that they have changed in the same way.

This is another point the beginner may be confused: multiple assignments.
Formally we play the same game with an int and a list, and they will again
react in a different way.
>>> n=m=8
>>> m*=8
>>> m
64
>>> n
8
>>> n=m=[2,3]
>>> m*=8
>>> m
[2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3]
>>> n
[2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3]


>
> One more thing.  Binding happens in an assignment, but it also happens in a
> function call, and in some import syntaxes and in for loops, generator
> expressions, and list comprehensions.

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?

Péter
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110608/d8b43da4/attachment-0001.html>


More information about the Tutor mailing list