Understanding the id function and the del keyword in Python

Understanding the id function and del keyword can give you a deeper understanding of how Python stores variables in the memory.

id function:

In Python, in a certain sense, everything is an object - variables, lists, functions: everything. Every object has a home in your computer’s memory and this home has a specific address. You can find this address by passing the object to the built-in id function .

Check it out in the following code snippet:

>>> a_list = [1, 8, 10, 9, 7]
>>> id(a_list)
140676641842432

Now, let’s see what happens when we try to store different objects in the same variable:

>>> id(max) # This is the built-in `max` function
140676642640592
>>> def max(list_name):
...     return 'No max value returned'
... 
>>> id(max)
140676613816976

We see that id(max) changed after we created the knockoff version of max. This indicates that our knockoff max was created at a new location in the memory.

(Note: If you run this on your computer, you’ll almost certainly get different results — that’s expected. If I repeat this experiment on my computer, I will also almost certainly get different results.)

Now, let’s add a few more lines and understand what Python does…

>>> max_val_test_0 = max(a_list)
>>> print(max_val_test_0)
No max value returned
>>> print(max(a_list))
No max value returned
  1. When you run max_val_test_0 = max(a_list) , you are assigning the result of max(a_list) to max_val_test_0 .
  2. But even before the assignment, something happens: max(a_list) is created. You can access its memory address by passing max_val_test_0 to id :
>>> id(max_val_test_0)
140676613962928

The object is created and it lives at 140676613962928 . The variable name max_val_test_0 is simply a way to access this address. At this moment, this address is independent of the address of knockoff max , it’s an entity on its own.

del keyword:

The del keyword allows us to delete objects.

Let’s delete our knockoff max and see what happens:

>>> del max
>>> print(max_val_test_0)
No max value returned
>>> id(max_val_test_0)
140676613962928
>>> id(max)
140676642640592

Note: the last output is the same address that I got when I ran id(max) at the beginning.

When you delete knockoff max , you’re simply clearing the house that sits at 140676613816976 , nothing happens to the object that lives in 140676613962928.

Now that max refers to the in-built max function again, the following behavior is expected:

print(max(a_list))
10

Continuing with our snippet:

>>> max_val_test_0 = max(a_list)
>>> print(max_val_test_0)
10
>>> print(max(a_list))
10

Now let’s check the address that max_val_test_0 refers to.

>>> id(max_val_test_0)
94877692666912

It’s something completely new!

I hope this helps.


This content was first created as a reply to this topic. It was reposted here to give it more visibility and help more people.

2 Likes