Editor

Count References

Advanced · Write the code · from How Python Works Under the Hood: Memory, GIL, and Bytecode

From the lesson: How Python Works Under the Hood: Memory, GIL, and Bytecode

Every time you type x = 42, a lot happens behind the scenes. Python creates an integer object in memory, assigns a reference to it, and manages its lifecycle automatically. Understanding these internals doesn't just satisfy curiosity -- it helps you write faster code, debug memory issues, and nail technical interviews.

Read the lesson

Write code that:

1. Creates a list data = [10, 20, 30]

2. Prints the reference count of data using sys.getrefcount()

3. Creates alias = data (a second reference)

4. Prints the reference count of data again

5. Deletes alias with del alias

6. Prints the reference count of data one more time

Note: sys.getrefcount() itself adds a temporary reference, so the count is always 1 higher than you might expect.

import sys
# Explore reference counting

More Internals exercises

All Python exercises · 50 practice problems · Advanced Python quiz