Learn How to Code with Python: Beginner to Advanced Guide

Memory is the physical substrate where your program’s data lives while it executes. At the hardware level, memory is organized as a linear sequence of bytes, and each byte has a numeric identifier called a memory address. A memory address is not mystical; it is simply an integer that the CPU uses to locate a specific byte. When we speak about “storing a variable,” what we really mean is that some bytes at specific addresses are being interpreted according to a type (integer, float, object, etc.). Understanding this removes abstraction fog and grounds your thinking in how machines actually operate. In high-level languages like Python, you are insulated from raw memory manipulation, but the underlying model still exists. When you create an object, Python allocates memory for it somewhere in the process’s address space. The variable name you write in code is not the object itself; it is a reference that points to an object located at a particular memory address. This distinction between name and object is fundamental. The operating system gives each process its own virtual address space. This means that the numeric addresses used inside one running program are isolated from others. Even if two processes both allocate an object at “0x7ffe1234,” those addresses refer to entirely different physical memory locations. Virtual memory allows safe multitasking and abstraction over hardware constraints. If you fail to internalize that variables are references to memory locations, you will misunderstand assignment, mutation, and object identity. Memory addresses are the anchor point that makes these behaviors coherent and predictable rather than magical. 1 A label for a function An integer identifying a specific byte in memory A type of Python variable A reserved keyword in Python What is a memory address? In Python, you can inspect an object’s identity using the built-in id() function. The value returned by id(obj) is an integer that uniquely identifies the object during its lifetime. In CPython, this integer typically corresponds to the object’s memory address, although the language specification does not require this behavior across all implementations. This detail matters because identity and equality are not the same concept. Two objects can have equal values but reside at different memory addresses. When you compare objects with the “is” operator, you are checking identity (i.e., whether two references point to the same address), not value equivalence. Consider small integers or short strings. CPython may reuse certain immutable objects for optimization. That means two variables assigned the same literal might reference the same memory address. This is an implementation detail, not a guarantee you should rely on in portable code. If you confuse identity with equality, your logic will break under subtle conditions. The id() function is your diagnostic tool for seeing how references and addresses behave at runtime. 1 The size of the object in bytes The memory address of the object (typically) The type of the object The value of the object What does id(obj) return in CPython? Assignment in Python does not copy objects by default. When you write a = b, you are copying a reference, not duplicating the underlying data. Both names now point to the same memory address. This is not a philosophical nuance; it is the core mechanism of Python’s object model. Because of this, mutating a mutable object through one reference affects all references pointing to that same address. For example, if two variables refer to the same list and you append to it using one name, the change is visible through the other. The memory address did not change; only the content at that address was modified. Immutable objects behave differently. When you “change” an immutable object, you are actually creating a new object at a different memory address. The original remains untouched. The variable is simply rebound to a new address. If you treat assignment as copying data rather than copying references, you will misinterpret bugs and waste time chasing illusions. 2 A deep copy of b is created A new object is always created The reference to b’s memory address is copied The value of b is deleted What happens when you execute a = b in Python? The distinction between stack and heap memory is often introduced in lower-level languages, but the conceptual framework is still useful in Python. The call stack holds frames for function calls, including local variable bindings. The heap is where objects are dynamically allocated. In CPython, most objects you create—lists, dictionaries, class instances—are allocated on the heap. The stack frame contains references to these heap objects, not the objects themselves. This architecture allows objects to outlive the function that created them if references are retained elsewhere. When a function returns, its stack frame is destroyed. However, heap-allocated objects remain as long as references to their memory addresses exist. This separation explains how closures and returned objects function. Understanding this distinction clarifies why local variables disappear after a function exits, yet objects can persist beyond that scope. 2 In CPU registers only On the call stack On the heap In the source code file Where are most Python objects stored? Garbage collection is the mechanism by which Python reclaims memory that is no longer reachable. In CPython, reference counting is the primary strategy. Each object keeps track of how many references point to its memory address. When the count drops to zero, the memory can be reclaimed. Reference counting is deterministic: as soon as the count hits zero, the object is eligible for destruction. However, circular references can defeat pure reference counting. That is why CPython also includes a cyclic garbage collector to detect and clean up reference cycles. The key concept is reachability. If no name or object references a particular memory address, it becomes garbage. The runtime can then free that memory for reuse. If you misunderstand reference counting, you may unintentionally retain references and create memory leaks, especially in long-running processes. 1 When its value becomes zero When its reference count drops to zero When its memory address changes When the program ends When is an object eligible for garbage collection in CPython? Mutable and immutable objects differ fundamentally in how memory addresses are handled during modification. A mutable object can change its internal state without changing its memory address. A list append operation modifies the same block of memory. An immutable object, such as an integer or string, cannot be modified in place. When you perform an operation that appears to change it, Python allocates a new object at a new memory address and rebinds the variable to that address. This distinction has performance implications. Mutating a large list can be more memory-efficient than repeatedly creating new objects. Conversely, immutability provides safety guarantees because no other reference can alter the underlying memory. Understanding which operations allocate new memory versus mutate existing memory is essential for reasoning about identity and performance. 2 Its memory address stays the same Its internal bytes are edited in place A new object is created at a new memory address The object is deleted immediately What typically happens when you modify an immutable object? Python’s “is” operator checks whether two references point to the same memory address. It does not check whether two objects have equal values. This is a strict identity comparison, not a semantic equivalence test. The “==” operator, by contrast, invokes the **eq** method to compare values. Two different objects at different memory addresses can still be equal under this operation. This is common with numbers, strings, and user-defined classes that implement equality. Confusing these operators leads to subtle bugs. For example, using “is” to compare integers may appear to work for small values due to interning, but fail for larger ones. Identity is about memory address; equality is about value semantics. If you are not deliberate about this distinction, you will write code that depends on implementation details rather than defined behavior. 2 Value equality Type compatibility Memory address identity Numeric equivalence What does the “is” operator check? Interning is an optimization technique where certain immutable objects are reused to avoid redundant allocations. In CPython, small integers and some strings are interned. This means multiple variables can reference the same memory address for identical values. Interning reduces memory consumption and can improve performance, but it is an implementation detail. The language specification does not guarantee that two identical literals will share the same address across all Python implementations. Relying on interning for correctness is a mistake. It may work in one interpreter and fail in another. Interning exists for efficiency, not as a semantic guarantee. If you need value comparison, use equality. If you need identity comparison, ensure you understand whether shared addresses are intentional or incidental. 1 Because interning deletes objects randomly Because interning is not guaranteed across implementations Because interning slows down execution Because interning changes object types Why is relying on interning for program correctness risky? When you pass arguments to a function in Python, you are passing object references. The function receives a new local name bound to the same memory address as the argument. There is no implicit copying of the object itself. If the object is mutable and the function mutates it, the changes are visible outside the function. If the function rebinds the local parameter to a new object, that rebinding does not affect the caller’s reference. This model is often described as “pass-by-object-reference” or “call-by-sharing.” The memory address remains the anchor point that determines shared state versus local rebinding. Misunderstanding this model leads to confusion about why some function calls appear to modify arguments while others do not. 2 A deep copy of the object The raw memory bytes A reference to the object’s memory address Only primitive values What is actually passed to a Python function? Low-level languages like C allow direct manipulation of memory addresses through pointers. Python does not expose raw pointers in normal usage, deliberately restricting direct memory access for safety. This abstraction prevents entire classes of errors such as segmentation faults and arbitrary memory corruption. However, the conceptual model remains pointer-based under the hood. Variables hold references, and references correspond to memory addresses. The difference is that Python enforces strict boundaries around how those addresses can be used. Through modules like ctypes, you can interact with raw memory, but this bypasses many of Python’s safety guarantees. Such tools should be used only when interfacing with external systems or performance-critical components. Understanding memory addresses in Python does not mean you manipulate them directly; it means you reason correctly about references and object identity. 1 To increase typing speed To prevent unsafe memory access and corruption To eliminate the need for variables To make memory addresses public Why does Python restrict direct pointer manipulation?

Edit