[Tutor] about copy.copy
Danny Yoo
dyoo at hkn.eecs.berkeley.edu
Tue Jul 18 17:39:32 CEST 2006
On Tue, 18 Jul 2006, linda.s wrote:
> But in the following example, a/b/c change and it looks like there is
> no difference.
>>>> a=[[1,2,3], [4,5,6]]
>>>> b=a
>>>> c=copy.copy(a)
Hi Linda,
I find it easiest to explain this by going to box-and-pointer diagrams.
Let me see if this will help you too.
First, some background: we'll say that a "name" is something that's
directed at a "value" such as a number or a list. We'll diagram this by
drawing an arrow from a name to a value. For example:
a = 42
will have a diagram of:
a -------------> 42
We'll treat a list as a value that itself can point at a lot of values.
For example:
a = [1, 2, 3]
is going to look like:
a ------------> [ . , . , . ]
| | |
V V V
1 2 3
So there's going to be two levels of arrows here. I'm using periods here
just as placeholders so you can see where the arrows are starting from.
Ok, with that background, we'll take a look at the diagram for:
a = [1, 2, 3]
b = a
c = copy.copy(a)
b
|
|
V
a ------------> [ . , . , . ]
| | |
V V V
1 2 3
^ ^ ^
| | |
c ------------> [ . , . , . ]
What's going on is that 'a' and 'b' are directed at the same list value.
'c' is directed at a different list value, but the elements of that new
list point to the same elements as 'a'. We call this a "shallow copy"
because the copying is only a single level deep.
This diagram tries to model what happens when we start mutating the list
value that 'a' points to. But let's say that we do a change to one of
those lists:
a[0] = 42
This mutates the first cell of the list to point to a value 42. What does
this look like? Try it out, and then look below to compare:
*** spoiler space ***
*** spoiler space ***
Ok, here's the diagram I have:
b
|
|
V
a ------------> [ . , . , . ]
| | |
V | |
42 | |
| |
V V
1 2 3
^ ^ ^
| | |
c ------------> [ . , . , . ]
It shows that 'c' is not going to "change" in the sense that we're not
going to observe any differences. It will have appeared, though, that
mutating the list that 'a' points to will affect 'b'.
Do you have any questions so far about this? Some kind of model like this
is necessary to understand the situation you're seeing now, so please feel
free to ask if any part of this is confusing.
More information about the Tutor
mailing list