You can't modify id
. The id
of an object is assigned at instantiation and cannot be changed during the object's lifetime. In CPython (the standard interpreter) it is actually the memory address of the object, so it is obvious why it can't change; in some other Python implementations, it is simply an auto-incrementing integer, but you still can't change it.
Python does reuse immutable objects sometimes, although this is an implementation detail unique to CPython and other Pythons (or even different versions of CPython) may behave differently. Since the integer object 2
can't be changed, it doesn't matter which instance you use in any given circumstance; for efficiency, Python therefore keeps a pool of "smallish" integers rather than always creating new ones. (Currently these are -5 to 256 inclusive.)
Strings are another type of object that can be reused. String literals are always reused, and you can force other strings to be reused with the intern()
function.
The empty tuple is another immutable object that is reused and always has the same id
.
What do you do if you need to change the id
of an object, and it's not one of those objects that Python always treats as singletons? Copy it. For some types this is easily done using the type itself; e.g. list(my_list)
creates a copy of my_list
that has a different ID. This is a shallow copy: if the list contained sublists, those aren't copied, but rather a reference to the same sublists appear in both the original list and the copy.
A list object can also be shallowly copied using slice notation, a la my_list[:]
(as can tuples and some other sequences).
When you need a full copy, or when you want to copy an object that doesn't have a built-in way to make a copy, the copy
module has you covered.