Python's id() Function
Python's id() function is an inherent tool, designed to fetch the unique identifier tied to a specific object.
Here's the deal: whenever you establish an object in Python, the language allocates it a one-of-a-kind identifier, or ID. This ID acts like a mailing address, marking out the memory slot where your object resides.
Every object you create in Python is graced with a unique identifier, and it'll hold onto this throughout your coding session or the program's runtime. Fascinating, isn't it?
If you find two variables sporting the same identifier, guess what? They're pointing to the same object.
So, how does this all work? Let's go hands-on and look at an example.
Kick things off by creating a variable and assigning a value:
x = "Hello, World!"
To peek at the object's identifier, all you need to do is call the id() function:
print(id(x))
What this does is it reveals the unique identifier attached to the string object referenced by the variable "x".
In this particular scenario, the identifier is the number 139694705876528.
139694705876528
Bear in mind that this number is unique. For the duration of your work session or the program's runtime, this number won't be re-assigned to another object.
Let's stir things up a bit. Create another variable, say "y", and assign it a different value.
y = "bye bye"
Unveil the identifier of this new object using our friend, the id() function.
print(id(y))
Since "y" points to a different object, it's only logical that it has a different identifier from "x".
139964847815920
This indicates that "x" and "y" are referencing different chunks of memory. These objects have their own, separate identifiers.
Before we proceed, there's an important caveat to note: the unique identifier retrieved by id() doesn't hold any special meaning beyond Python's current implementation. This means the identifier might be different across various runs of the same program or different versions of Python. Also, there's no cast-iron guarantee that two distinct objects will carry different identifiers for their entire lifespan. However, Python does promise that, for the lifespan of an object, its identifier will remain unique and unchanged.
But what if two variables end up with the same identifier?
Well, two variables will share an identifier if they're both pointing to the same object.
x = "Hello, World!"
y = x
In this example, "y" is referencing the same object as "x".
When we print the identifiers of both objects,
print(id(x))
print(id(y))
The id() functions reveal an identical identifier number for each.
139694705876528
139694705876528
This strongly suggests that both variables are referring to the same object in memory.
So, our variables are like twin pointers, both aiming at the same memory object.
Lastly, a quick note about identifiers: an ID is not the actual memory address, but a unique number assigned by Python to a memory slot when a new object is created.