Sharing data between two lists
First let me say that I thought that the way data storage worked in python is that everything is an object so there is no need for such things as pointers. If you pass an piece of data into a function then that function has the real piece of data. When you exit out of that function it the data passed in could have been modified.
Now I was working with lists and I thought that if I put the same piece of data on two lists then modifying it in one place would modify it in the other.
How can I have one piece of data that is on two, or more, different lists? I would开发者_如何学Go want to change this data in one place and then have the other change.
For example take the following:
p = 9
d = []
f = []
d.append(p)
f.append(p)
print 'd',d
print 'f',f
p = 3
print 'd',d
print 'f',f
When this is run the output is:
d [9]
f [9]
d [9]
f [9]
I would like the second set of data to be 3 but it doesn't seem to work. So where in my thought process did I go wrong? Is there an implicit copy operation when putting data onto a list?
First of all, integers (really, number objects) are immutable. There is no "modifying" this "data". Second of all, there is also in Python the notion of name binding. When you do:
p = 9
Two things happen: first, a number object (9
) is created; second, it is then bound to the name p
.
When you later do:
p = 3
It does not, as you think, "modify" the immutable number object created earlier. What this simply does is, again, two things: first, a new number object (3
) is created; second, it is then bound to the name p
.
Pictorally:
(1a) 9
(1b) p --> 9
(2a) p --> 9
3
(2b) 9
p --> 3
Your second assignment doesn't change the value of the object bound to p
, it rebinds p
to a whole new object. d
and f
still contain references to the old object, which still has the same value.
精彩评论