Python Memory Management and Tips Transcripts
Chapter: Python variables and memory
Lecture: The id() function
Login or
purchase this course
to watch this video and the rest of the course contents.
0:00
Let's real quickly look at the documentation from Python's docs around this id built-in
0:07
function, and it says "id is a function that takes a single object".
0:11
And if you look at the description,
0:12
it says "it will return the identity of the object.
0:15
This is gonna be a number which is guaranteed to be unique and constant during the objects
0:20
Lifetime, however, two objects may with non-overlapping lifetimes may have the same
0:27
id value". That's more likely than just random places in memory.
0:30
As you'll see, there's patterns that have a tendency to reuse memory rather than allocate
0:35
new memory. Nonetheless, this while the objects are around,
0:39
what this number come back means this is the unique identity of
0:43
the object. And if you get two objects and you ask from them and they're
0:46
the same, they're literally the same object in the runtime.
0:50
If those numbers are different, even if they would test for equality like two strings
0:54
might be equal equal to each other
0:56
but they're not the same location of memory,
0:58
potentially, then the id would come back to be different. And, little special detail here
1:04
at the end, if you happen to be in CPython,
1:07
The CPython implementation detail is that this is the memory address,
1:11
the address of the object in memory.
1:13
So this literally is the base 10 version of "Where's This Thing in Memory?"
1:19
Id is simple, but we're gonna be using it a couple of times throughout this course
1:22
to ask questions like "are these actually the same thing?"
1:25
or "where do they live in memory?" and stuff like that.
1:27
So, here's the deal.