Understanding Object Identity and Memory Addresses
In this lesson, you will learn how to use the id() function to peek under the hood of Python and discover the unique memory address of your objects.
In previous lessons, we learned that variables are simply labels pointing to objects in your computer's memory. While two variables might hold the same value, they could potentially point to different objects. To see exactly where an object lives in your computer's memory, Python provides a built-in function called id().
Using the id() function
The id() function returns a unique integer that represents the memory address of an object. As long as an object exists in memory, its ID will remain constant.
Consider this example:
x = 100
y = 100
print(id(x))
print(id(y))
If you run this code, you might notice that both variables produce the same ID. This is because Python is clever; for small integers, it often reuses the same object in memory to save space. However, if you create larger objects or different types, you might see them occupying different spots.
Value vs. Identity
It is important to distinguish between what an object is and what an object holds. The value is the data (like the number 100), but the identity is its unique location in your system's RAM.
Think of it like two identical houses on a street. They might look exactly the same on the outside (the same value), but they are located at different plot numbers (the identity). If you paint one house, the other remains unchanged because they are physically distinct objects, even if they share the same blueprints.
By using id(), you can verify if two variables are referring to the exact same object in memory or just objects that happen to have the same content.
Key Takeaway: The id() function returns a unique integer representing an object's specific memory address, allowing you to distinguish between an object's value and its unique identity in the computer's memory.