This lesson is from the Real Python video course by Martin Breuss.
Object Value vs Object Identity
00:00 Welcome to section 3, where we’ll talk about object identity. This is still part of our deeper dive, where we see a bit of what is actually going on when we assign a variable in Python.
00:10 There’s a couple of points that I want to talk about. Most importantly, you will learn about what’s an object value versus what is an object’s identity.
00:19 And then we’re going to go a bit into the weeds. Small integer caching is a weird thing in Python that might trip you up, and I think it’s quite fun if you know about it, so you will learn about how does that work.
00:31 And I’ve also got a little challenge for you, a Python pub quiz question that you can work out by yourself, and there’s also some solutions provided. So, let’s get going. First of all, let’s look at what is an object’s value versus what is its identity. For this, I’m heading over to an IPython session. It’s a new one, and so I’ll assign again the variables that we’ve worked with before.
00:56
n = 300
and m = 400
, let’s say.
01:02
So, the value of n
is what I get when I just put it into the interpreter. This is its value, what it points to, the integer object it points to.
01:12
And it has the value of 300
. Now, every object in Python has a certain identity. It has a place in memory where it lives, and we can figure out that place in memory by saying id()
and then passing in either the object or the reference to the object. So this is just a long string of numbers, right?
01:30
But this tells us specifically where in memory does this object live. And this object, in that case, is the integer object 300
. So, what we would expect… If I say n = 300
, then I create an integer object 300
. And I say m = 300
, I create another integer object 300
.
01:54
And they both point to different objects in memory. If I would say id(n)
, I get some kind of number, and if I say id(m)
, I get a different number, you see?
02:05
So this is just showing us that those are two different objects, two different integer objects. Now, what we can see here is that even though both n
and m
have the same value, they have different object identity.
02:20
The way that we compare for a value, whether it’s the same value, is with the double equal sign (==
). I can say n == m
. It gives a result True
, because 300
is the same as 300
, the value. However, we know that those are two different objects.
02:39
So if I say the id(n) == id(m)
, we’re getting False
. So even though these two variables have the same value, they don’t have the same identity. And this is kind of what we would expect, all right? That makes sense. But now comes the weird part.
You must own this product to join the conversation.