[Tutor] Problem with copy
Wed, 22 Aug 2001 01:20:38 +0200
On 0, Bill Ferreira <firstname.lastname@example.org> wrote:
> "copy" is not making a copy until I change the source value so I guess I'm
> doing something wrong, any suggestions?
> >>> import copy
> >>> x=1
> >>> ix=copy.copy(x)
> >>> ix is x
> My understanding is that the purpose of copy is to insure that the target
> object (ix in this case) is a different object than the source object (x).
> If I follow up the above code with the following:
> >>> x = 2
> >>> x is ix
> It certainly seems to me that the "is" operator should have returned 0 in
> both cases. And now:
> >>> x = 1
> >>> x is ix
> What's going on here?
In short, all object in your program that are the integer 1 will be the same
object. It's cached.
This is true for all numbers -1 to 100, if I recall correctly, in the
current version. It's also true for interned strings, and other exceptional
This is never a problem - since integers are immutable, it doesn't matter if
two variables that have value 1 happen to refer to the same object.
copy() is meant to be used on more complex data structures, like lists; so
that changing the new list doesn't change the old one. Immutables like
integers can't be changed anyway, so copying isn't very useful on integers,
it just takes extra memory space.
Without knowing what you're trying to do, I can't give more than this kind
of general comment...