[Tutor] Is there any logic in this?
alan.gauld at btinternet.com
Sat Sep 1 18:05:07 CEST 2007
"Righard/Riku van Roy" <pluijzer at gmail.com> wrote
> If you copy a list into another variable, and then change the second
> one, the first gets changed as well, for example:
>>>> a = [10, 40, 30, 20]
>>>> b = a
This is not a copy its a name assignment.
You have created a list object and assigned
the name 'a' to it.
Then you created a new name 'b' and told it
to refer to the same object as 'a'. You did not
create any new objects, you did not copy
To copy a list in Python you must use the copy
function or use a slice [:] (as you do below).
You can check this with the id() function in Python:
>>> a = [1,2,3]
>>> b = a
So they have the same id, they are the same object.
> this happens with dictionary's too, but not with intergers,
It does happen with integers (and strings etc) too.
But integers and strings are immutable, you cannot
change the object you can only create new objects.
>>> x = 42
>>> y = x
Notice the same id, the same object
b.sort() changes the data ordering inside the list
object. It does not change the list object itself.
Still the same id as above, the same object.
Only the data contained by the list has changed.
You can do that because lists are mutable, they
can be changed.
But integers are not mutable, you can only
create new integers:
>>> y = 2*x
A different id, we have created a new integer object
>>>> b = a[:]
Thats correct, here you really do create a copy of a.
> ...but I wonder if there is any logic behind this, I cannot find a
> practical use for it, just problems.
There are a few situations where it is useful, but mainly
it saves memory. However I don't think the memory saving
is the main reason its built that way, its a model of thinking
about names that moves us away from thinking about
variable names as being aliaes for memory locations.
It makes the computing machine more abstract and
therefore more portable and keeps p[rogrammes focused
on solving core problems rather than directing the
PS. For an entirely different explanation of Python's
naming concept try reading the section on variables
in my raw materials tutor topic...
Author of the Learn to Program web site
More information about the Tutor