Sitemap
Stackademic

Stackademic is a learning hub for programmers, devs, coders, and engineers. Our goal is to democratize free coding education for the world.

Python: Memory Management (Part 2.1)

6 min readAug 20, 2026

--

Press enter or click to view image in full size
C showing Python around the memory management department!!

This article tells you about the witchcraft done by the Python creators to make Python what it is today—specifically, how every created variable and data structure is spread across memory and the inner layer of management that talks with the OS.

Part 1 was about knowing how everything is an object in Python and how they are referred to. Please read Part 1 before jumping ahead into this article.

This article is all about memory management (Part 2), divided into 3 medium articles.

Welcome back!!

This particular one will answer who is behind memory management, the underlying structures of data types, and what integer and string interning actually means in Python.

Reminder: We are discussing CPython powered by C as core. And we have malloc() in C, which is responsible for memory allocation, and free() for freeing up memory.

In Python, there are wrappers around these functionalities, which help Python manage its memory.

How are these wrappers responsible for memory management, and what are they called?

These wrappers—or, I should say, domains—serve different purposes in layers, starting from the OS, down to assigning objects their memory locations and referencing them to variable names.

The domain architecture is divided into 5 parts:

  • System Allocator or System Domain
  • Raw Domain
  • Mem Domain
  • Object Domain
  • Garbage Collector

Note: I am not going into the deep technical structure of these domains and how they interact with Python just yet, but rather giving an eagle-eye view of how they behave.

  • System Domain: The base layer interacting with the OS (Windows/Linux) to allocate large chunks of memory. Whatever memory is asked for here is not known to the garbage collector. This borrowed memory is called the private heap, which will majorly be used by the Mem Domain and Object Domain.
  • Raw Domain: A wrapper around the System Domain. It is responsible for handling all sorts of errors and checking for any memory issues within the process of memory handling and borrowing. PyMem_RawMalloc is used for interacting with the Raw Domain (mostly used by C-extensions).
  • Mem Domain: This is a quite interesting domain that looks over allocating memory from the private heap for general-purpose buffers.
  • In case you don’t know what buffers are:
    Think of them as arrays of 0s and 1s, which are later converted to readable strings. Buffer-type data is mostly related to input and output operations, e.g., reading a file.
  • Object Domain: This is the best friend of all the objects created and is responsible for living up to the famous slogan: “Everything in Python is an object.” This domain assigns allocations for all the objects present in Python.
  • Garbage Collector: Handles object cleanup via reference counting (immediate deallocation when references hit zero) and a cyclic garbage collector (to clean up isolated reference loops).

Before seeing how these domains work together (will be covered in next part ),

Let's get into the inner structures of the data types we have in Python.

This will crystalize our concept of memory management. I will be covering the basics, but it will be enough for concept mapping in our brains.

In the last article, I discussed briefly how lists and tuples look and how variables are just pointers to the object assigned to them. Let’s bring that same concept back and establish the connection here!

Press enter or click to view image in full size

The base object structure in CPython is common across all objects but changes when the type of data changes, like for lists and tuples.

Let’s start with integers in Python.

Integer Interning or Small Int Cache

In Python, integers sometimes show an interesting referencing behavior, which was added by Python developers for optimization.

It’s not a huge mystery:

Before starting out, the interpreter caches—meaning it pre-allocates—integer values from -5 to 256.

Because these numbers are generally used heavily in loops and as standard values, it is much faster to reference them when they are already created. We don’t need to worry about a thing, but it was fascinating to me when I first came across this term.

Get Ruchi DEO’s stories in your inbox

Join Medium for free to get updates from this writer.

Here is a quick example of how integer interning looks in action:

Here is a quick example of how integer interning looks in action:

# Integer Interning in Action
a = 256
b = 256
print(a is b) # True! Both point to the exact same cached object in memory.

c = 257
d = 257
print(c is d) # False! 257 is outside the -5 to 256 range, so two separate objects are created.

Many curious minds might be asking: what happens with decimal values (floats)?

Well, it comes down to predictability and mathematics. Think about it!

A = 10.22, B = 10.2234

They are different but still start with 10. For this, we need different objects; you can’t have them all already stored, or your precision calculations will go wrong! You don’t want that, right?

One more thing I missed!

Interning is heavily tied to the “is” operator in Python.

  • == checks if two objects have the same value.
  • “is” checks if two objects share the same memory address.

Because specific integers and strings are interned, doing x is y is a very fast way for Python’s internal C code to check if two things are identical without having to read their actual values.

However, because of the imprecision mentioned above, checking if two floats share an identity is a massive anti-pattern in programming.

Developers are taught to never use it with floats and often shouldn’t even use == (instead, they use math.isclose() to check if floats are “close enough”).

Since the language discourages checking float identity, the developers have no reason to optimize memory addresses to match.

String Interning

Storing or caching strings happens in two stages:

  1. Static Interning (Startup): A few strings, like “a” or “1” (and empty strings), are pre-stored. These are placed into a permanent, hidden C dictionary (a hash table) known as the “interned dictionary.”
  2. Dynamic Interning (Runtime): When Python parses your code, it automatically interns strings that look like identifiers (variable names, function names, dictionary keys).

The Process:

  • If you type my_var = "hello" Python allocates memory for the string “hello”.
  • Before giving it to you, Python checks the hidden “interned dictionary.”
  • If “hello” is already in there, Python immediately destroys the newly allocated object and gives you the pointer to the existing one.
  • If it is not in there, Python adds your newly allocated string to the dictionary so future identical strings will share this memory.

Is every string interned then?

Well, no! It is mostly short strings containing only letters, numbers, and underscores without spaces. Strings with spaces, punctuation, special characters, or very long strings read from files are created normally and destroyed when not in use.

Let’s look at a quick example:

# String Interning in Action
str1 = "hello_world"
str2 = "hello_world"
print(str1 is str2) # True! It looks like an identifier (no spaces), so it is automatically interned.

str3 = "hello world!"
str4 = "hello world!"
print(str3 is str4) # False! Because of the space and exclamation mark, Python creates two separate objects.

What is with the dictionary thing? Well, that dictionary is only for referencing the string. The string object is made normally; just its reference is stored. If a second string with the exact same characters is found, the new one will be destroyed and the variable will be referred to the earlier one.

Take the example of basic_string = “pie”:

  • Evaluation: Python evaluates the string “pie” and determines it fits the criteria for automatic interning (it contains only letters).
  • Logging: Python adds a new entry into the interned dictionary.
  • Reuse: If you create another_string = “pie” later in the code, Python checks the dictionary, finds the existing address, and simply points the new variable to the exact same block in memory, bypassing allocation entirely.

Easy, and we don’t even know these things are happening behind the scenes!

Well, that’s it for now.

Originally I wanted one whole article for memory management.
(I thought it was possible, until reality kicked me!! 🥲).

But hey! Long articles get boring, right? 😅😅

I will bring in the new part covering the rest of the structures and the working of these domains, connecting all the dots together ASAP.

Till then, have fun with Python.

See yaa!! 👋

Ruchi DEO
Ruchi DEO

Written by Ruchi DEO

A developer with an interest in design, AI developments, and reverse engineering a vast array of tools and software and how to solve a problem!!

Stackademic
Stackademic

Published in Stackademic

Stackademic is a learning hub for programmers, devs, coders, and engineers. Our goal is to democratize free coding education for the world.