Zum Hauptinhalt springen
tsecurity.de LIVE
Echtzeit-Radar & Feeds
Alle RSS Feeds
👥 Community & Social
Sichere ProgrammierungTCP vs UDP: The Two Ways to Move Data, and Why Neither Is "Better"(21.09.2026 um 09:31 Uhr)
Sichere ProgrammierungBukan Sekadar Variabel, Tapi Nyawa dari Aplikasi Kamu! 🚀(21.09.2026 um 09:36 Uhr)
Sichere ProgrammierungAI voice agent for customer service: what stops callers hanging up?(21.09.2026 um 09:42 Uhr)
Sichere ProgrammierungReading a small model's confidence instead of its prose(21.09.2026 um 09:47 Uhr)
Sichere ProgrammierungTCP vs UDP: The Two Ways to Move Data, and Why Neither Is "Better"(21.09.2026 um 09:31 Uhr)
Sichere ProgrammierungBukan Sekadar Variabel, Tapi Nyawa dari Aplikasi Kamu! 🚀(21.09.2026 um 09:36 Uhr)
Sichere ProgrammierungAI voice agent for customer service: what stops callers hanging up?(21.09.2026 um 09:42 Uhr)
Sichere ProgrammierungReading a small model's confidence instead of its prose(21.09.2026 um 09:47 Uhr)
Intelligence View
⚡ tsecurity.de Intelligence

Demystifying Python’s Memory Model: Mutability, Identity, and Function Arguments

When you first start programming in Python, everything feels intuitive. You assign a value to a variable, use it, and move on. However, underneath Python's clean syntax lies a strict set of rules governing how data is stored, referenced,…

0
↗ Quelle (dev.to)
Reagiere als Erste:r — dein Feedback zählt!

When you first start programming in Python, everything feels intuitive. You assign a value to a variable, use it, and move on. However, underneath Python's clean syntax lies a strict set of rules governing how data is stored, referenced, and manipulated in memory. Understanding these mechanics is the dividing line between writing buggy code and writing highly optimized, predictable Python programs. This post breaks down the core concepts of Python's memory model, exploring object identity, mutability, and how data moves through functions.



Understanding id and type

In Python, absolutely everything is an object—from numbers and strings to functions and lists. Every object created in memory is automatically assigned three things: a value, a data type, and a unique identification number. You can inspect these properties using the built-in type() and id() functions. The type() function tells you the class of the object, while id() returns its unique memory address (in CPython, this corresponds to the object's location in RAM).






a = [1, 2, 3]

type(a)



id(a)

139926795932424



b = a

id(b)

139926795932424

As shown in the example above, when we assign b = a, Python does not duplicate the list. Instead, it copies the memory reference. Both variables now point to the exact same memory address, meaning a is b evaluates to True.










Mutable Objects

Mutable objects are data structures that can be modified in place without changing their identity (memory address). Common examples of mutable objects in Python include lists (list), dictionaries (dict), sets (set), and byte arrays. When you append an element to a list or update a key in a dictionary, you are directly altering the existing object in memory.



Python






l1 = [1, 2, 3]

print(id(l1))

140531824638784



l1.append(4)

print(l1)

[1, 2, 3, 4]

print(id(l1))

140531824638784

Notice how the list's contents changed from [1, 2, 3] to [1, 2, 3, 4], but the id() remained exactly the same. Because mutable objects can change, copying their reference carelessly (e.g., l2 = l1) means updates to one variable will unexpectedly modify the other.










Immutable Objects

In contrast, immutable objects cannot be altered once they are created. Examples include integers (int), floats (float), strings (str), tuples (tuple), and frozen sets (frozenset). If you attempt to alter an immutable object, Python is forced to build a brand new object at a completely different memory address and redirect your variable to it.



Python






a = (1, 2)

print(id(a))

139926795932424



a = a + (3,)

print(a)

(1, 2, 3)

print(id(a))

139926795938112

In this snippet, appending 3 to the tuple looks like a modification, but the changing id() proves that Python secretly created a whole new tuple (1, 2, 3) behind the scenes.










Why It Matters and How Python Treats Them Differently

Understanding mutability is crucial because Python optimizes memory allocation based on whether an object can change. Since immutable objects are safely locked down, Python heavily utilizes memory optimization tricks like string interning and integer caching. For instance, Python pre-loads small integers (from -5 to 256) and empty tuples into a shared global pool.



Python






x = ()

y = ()

x is y

True



num1 = 100

num2 = 100

num1 is num2

True

Because x, y, num1, and num2 are immutable, Python points identical values to the exact same pre-existing object to save RAM. If these were mutable lists, Python would never risk sharing memory addresses because a change to one would break the other.










How Arguments Are Passed to Functions

Python employs a mechanism known as pass-by-assignment (or pass-by-object-reference) when handing variables over to functions. This means the function parameter receives a copy of the memory address of the argument. What happens next depends entirely on whether that object is mutable or immutable.



If you pass a mutable object to a function and mutate it inside (e.g., using .append()), the changes persist outside the function:



Python

def increment_list(n):

n.append(4)



l = [1, 2, 3]

increment_list(l)

print(l) # Output: [1, 2, 3, 4]

However, if you pass an immutable object—or if you completely reassign a mutable variable inside the function using the = operator—you only change the local variable's shortcut. The outer scope remains completely untouched:



Python

def assign_value(n, v):

n = v # Rebinds the local name 'n' to point to 'v'



l1 = [1, 2, 3]

l2 = [4, 5, 6]

assign_value(l1, l2)

print(l1) # Output: [1, 2, 3]

Deep Dive: Advanced Python Optimization Techniques

Moving beyond the basics, diving into Python's implementation details reveals fascinating architectural decisions, specifically regarding the memory layouts of CPython's core types. For instance, NSMALLPOSINTS and NSMALLNEGINTS are specific macros in the C source code that handle the compilation-level caching of integers. Furthermore, looking into special cases like tuple immutability reveals a unique nuance: while a tuple itself is structurally immutable and cannot have its references swapped, it can contain a mutable object (like a list) as an element. If you modify the list inside that tuple, the list changes in place, yet the tuple’s identity remains intact—highlighting that immutability guarantees the integrity of the references the tuple holds, not necessarily the values inside those references.



To read more about Python internals and keep up with my engineering journey, follow my updates here and connect with me on social media!

Ähnliche Beiträge
🔍 Verwandte News

Auch interessante Nachrichten Demystifying Python’s Memory Model: Mutability, Identity, and Function Arguments

Thematisch verwandte Begriffe: Demystifying, Pythons, Memory, Model · 6 Treffer

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Zum Aktualisieren ziehen
ZERO-DAY CVE-2026-94030 | A security vulnerability has been detected in SerenityOS up to 3d83e4509…
Advisory →
TTS Reader • tsecurity.de Voice
tsecurity.de Icon
tsecurity.de App
Offline-Lesen, Eilmeldungen & 0ms Ladezeit

Installiere tsecurity.de direkt auf deinen Home-Bildschirm für das ultimative Vollbild-Magazinerlebnis ohne Browser-Leisten.

Nächster Beitrag
Themen-Radar & Intelligence Matrix
Echtzeit-Taxonomie nach Angriffsvektoren & Plattformen

tsecurity.de Live Threat Radar

🔴 LIVE RADAR
MONITORING
AKTIV
CVE-DATENBANK
LIVE
🔍
Community Radar & Live Chat
Sentinel Bot online • Live-Stream
Dein Cluster: Security Explorer
Match:
lädt…
Verbindung zum Community-Stream wird aufgebaut...
Bearbeitungsmodus — Senden überschreibt deine Nachricht
Community-Puls — was gerade passiert
lädt…
Aktivitäten deiner Analysten
lädt…
Neues Thema oder Eilmeldung einreichen

Reiche interessante Links, Zero-Days oder Debatten ein. Die Community entscheidet per Upvote über die Veröffentlichung.

Heiß diskutierte Einreichungen
🔖 Gespeicherte Artikel
📂 Keine gespeicherten Artikel vorhanden.
Zurück Ziehen Vor
Links: vorheriger Artikel Rechts: nächster Artikel unten: schließen
News NIS-2 Frühwarnung Tier-1 Intel ⏱️ 3 Min vor 10 Min
Artikeldaten werden geladen...

Zurück: vorheriger Vor: nächster
↗ Original-Quelle
Social Reaktionen Deine Reaktion zählt
Einstufung & Relevanz-Poll 0 Stimmen
In sozialen Netzwerken teilen 1-Klick