<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by D Ganza on Medium]]></title>
        <description><![CDATA[Stories by D Ganza on Medium]]></description>
        <link>https://medium.com/@d.ganza1?source=rss-75ee2e2f27a3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*BeXpcophGOelte8T</url>
            <title>Stories by D Ganza on Medium</title>
            <link>https://medium.com/@d.ganza1?source=rss-75ee2e2f27a3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 05:49:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@d.ganza1/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Mutable, Immutable… Everything Is an Object in Python.]]></title>
            <link>https://medium.com/@d.ganza1/mutable-immutable-everything-is-an-object-in-python-136cad3846ca?source=rss-75ee2e2f27a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/136cad3846ca</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[mutable-objects]]></category>
            <category><![CDATA[immutable-vs-mutable]]></category>
            <dc:creator><![CDATA[D Ganza]]></dc:creator>
            <pubDate>Tue, 17 Nov 2026 08:52:08 GMT</pubDate>
            <atom:updated>2026-11-17T08:52:08.961Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uQaXj1xxFSdsxSSyuV-YdQ.png" /></figure><h3>Introduction</h3><p>When I started writing Python, I thought of a variable as a box that holds a value. Then I ran this:</p><pre>&gt;&gt;&gt; l1 = [1, 2, 3]<br>&gt;&gt;&gt; l2 = l1<br>&gt;&gt;&gt; l1.append(4)<br>&gt;&gt;&gt; l2<br>[1, 2, 3, 4]</pre><p>I never touched l2, yet it changed. The &quot;box&quot; model is wrong. In Python, <strong>everything is an object</strong>: numbers, strings, lists, functions, even classes. A variable is not a box; it is a <strong>name</strong> (a label) that refers to an object living somewhere in memory. Once you see variables that way, a lot of &quot;weird&quot; Python behaviour suddenly becomes logical. In this post I go through what I learned: id and type, mutable and immutable objects, why the difference matters, and how arguments are passed to functions.</p><h3>id and type</h3><p>Every object in Python has three things: an <strong>identity</strong>, a <strong>type</strong> and a <strong>value</strong>.</p><p>type() tells you what kind of object it is. The type decides what operations the object supports and whether it can be changed:</p><pre>&gt;&gt;&gt; type(89)<br>&lt;class &#39;int&#39;&gt;<br>&gt;&gt;&gt; type(&quot;Best School&quot;)<br>&lt;class &#39;str&#39;&gt;<br>&gt;&gt;&gt; type([1, 2])<br>&lt;class &#39;list&#39;&gt;<br>&gt;&gt;&gt; type((1, 2))<br>&lt;class &#39;tuple&#39;&gt;</pre><p>id() returns the object&#39;s identity: an integer that is unique for that object for as long as it lives. In CPython (the standard interpreter) it is simply the object&#39;s <strong>memory address</strong>:</p><pre>&gt;&gt;&gt; a = [1, 2, 3]<br>&gt;&gt;&gt; id(a)<br>139926795932424<br>&gt;&gt;&gt; hex(id(a))<br>&#39;0x7f433ef75308&#39;</pre><p>(Your numbers will be different. They are addresses, so they change every run.)</p><p>Two operators go with these ideas. == compares <strong>values</strong>; is compares <strong>identity</strong>, meaning &quot;are these the exact same object?&quot; (the same as id(a) == id(b)):</p><pre>&gt;&gt;&gt; l1 = [1, 2, 3]<br>&gt;&gt;&gt; l2 = [1, 2, 3]<br>&gt;&gt;&gt; l1 == l2<br>True<br>&gt;&gt;&gt; l1 is l2<br>False</pre><p>Same value, two different objects.</p><h3>Assignment vs referencing: names and aliases</h3><p>Before talking about mutability, one key idea: <strong>assignment never copies an object</strong>. b = a does not create a new object. It makes the name b refer to the object that a already refers to. Now the object has two names. These extra names are called <strong>aliases</strong>.</p><pre>&gt;&gt;&gt; l1 = [1, 2, 3]<br>&gt;&gt;&gt; l2 = l1          # referencing: l2 is an alias of l1<br>&gt;&gt;&gt; l1 is l2<br>True</pre><p>Memory schema:</p><pre>names            objects in memory<br> ┌────┐<br> │ l1 │──────┐<br> └────┘      │     ┌─────────────────────┐<br>             ├────▶│ list  [1, 2, 3]     │  id 0x7f…308<br> ┌────┐      │     └─────────────────────┘<br> │ l2 │──────┘<br> └────┘</pre><p>Assigning a <em>new</em> object to a name, on the other hand, just moves that one label. The other alias is not affected:</p><pre>&gt;&gt;&gt; l1 = [1, 2, 3]<br>&gt;&gt;&gt; l2 = l1<br>&gt;&gt;&gt; l1 = l1 + [4]    # l1 + [4] builds a NEW list; l1 now points to it<br>&gt;&gt;&gt; l1<br>[1, 2, 3, 4]<br>&gt;&gt;&gt; l2<br>[1, 2, 3]</pre><pre>┌────┐            ┌─────────────────────┐<br> │ l2 │───────────▶│ list  [1, 2, 3]     │  (old object)<br> └────┘            └─────────────────────┘<br> ┌────┐            ┌─────────────────────┐<br> │ l1 │───────────▶│ list  [1, 2, 3, 4]  │  (new object)<br> └────┘            └─────────────────────┘</pre><p>Whether you <em>change an object</em> or <em>move a name to another object</em> is exactly where mutability comes in.</p><h3>Mutable objects</h3><p>A <strong>mutable</strong> object can be changed in place after it is created. Its value changes, but its identity (its id) stays the same.</p><p>Mutable built-in types: <strong>list, </strong><strong>dict, </strong><strong>set and </strong><strong>bytearray</strong> (plus instances of most classes you write yourself).</p><pre>&gt;&gt;&gt; l = [1, 2, 3]<br>&gt;&gt;&gt; before = id(l)<br>&gt;&gt;&gt; l.append(4)<br>&gt;&gt;&gt; l[0] = 99<br>&gt;&gt;&gt; l<br>[99, 2, 3, 4]<br>&gt;&gt;&gt; id(l) == before<br>True</pre><pre>&gt;&gt;&gt; d = {&quot;a&quot;: 1}<br>&gt;&gt;&gt; before = id(d)<br>&gt;&gt;&gt; d[&quot;b&quot;] = 2<br>&gt;&gt;&gt; d, id(d) == before<br>({&#39;a&#39;: 1, &#39;b&#39;: 2}, True)</pre><pre>&gt;&gt;&gt; s = {1, 2}<br>&gt;&gt;&gt; before = id(s)<br>&gt;&gt;&gt; s.add(3)<br>&gt;&gt;&gt; s, id(s) == before<br>({1, 2, 3}, True)</pre><pre>&gt;&gt;&gt; ba = bytearray(b&quot;hi&quot;)<br>&gt;&gt;&gt; ba[0] = 72          # 72 is the code for &#39;H&#39;<br>&gt;&gt;&gt; ba<br>bytearray(b&#39;Hi&#39;)</pre><p>Because the object itself changes, <strong>every alias sees the change</strong>. That is why l2 changed in the introduction.</p><p>The same goes for += on a list. For lists, += extends the list in place, unlike l = l + [...], which builds a new one:</p><pre>&gt;&gt;&gt; a = [1, 2, 3]<br>&gt;&gt;&gt; before = id(a)<br>&gt;&gt;&gt; a += [4]<br>&gt;&gt;&gt; id(a) == before<br>True</pre><pre>&gt;&gt;&gt; a = [1, 2, 3, 4]<br>&gt;&gt;&gt; before = id(a)<br>&gt;&gt;&gt; a = a + [5]<br>&gt;&gt;&gt; id(a) == before<br>False</pre><h3>Immutable objects</h3><p>An <strong>immutable</strong> object can never be changed after it is created. Any operation that looks like a change actually builds a <strong>new object</strong> and moves the name to it.</p><p>Immutable built-in types: <strong>numbers (</strong><strong>int, </strong><strong>float, </strong><strong>complex), </strong><strong>str, </strong><strong>tuple, </strong><strong>frozenset and </strong><strong>bytes</strong> (and bool, which is a kind of int).</p><pre>&gt;&gt;&gt; n = 89<br>&gt;&gt;&gt; before = id(n)<br>&gt;&gt;&gt; n += 1<br>&gt;&gt;&gt; n, id(n) == before<br>(90, False)</pre><pre>&gt;&gt;&gt; s = &quot;Best&quot;<br>&gt;&gt;&gt; before = id(s)<br>&gt;&gt;&gt; s += &quot; School&quot;<br>&gt;&gt;&gt; s, id(s) == before<br>(&#39;Best School&#39;, False)</pre><pre>&gt;&gt;&gt; s[0] = &quot;b&quot;<br>TypeError: &#39;str&#39; object does not support item assignment<br>&gt;&gt;&gt; t = (1, 2, 3)<br>&gt;&gt;&gt; t[0] = 9<br>TypeError: &#39;tuple&#39; object does not support item assignment</pre><pre>before n += 1               after n += 1</pre><pre> ┌───┐     ┌──────────┐      ┌───┐     ┌──────────┐<br> │ n │────▶│ int  89  │      │ n │──┐  │ int  89  │  ← freed when no<br> └───┘     └──────────┘      └───┘  │  └──────────┘    name refers to it<br>                                    │  ┌──────────┐<br>                                    └─▶│ int  90  │  ← brand-new object<br>                                       └──────────┘</pre><p><strong>How an immutable object is stored in memory.</strong> In CPython every object starts with the same header: a <em>reference count</em> (how many names and containers point to it) and a pointer to its <em>type</em>. After the header comes the value itself: the digits of an int, or the length, cached hash and characters of a str. For an immutable object that value is written once, when the object is created, and never touched again. That is why Python can safely <strong>share</strong> one immutable object between many names: nobody can change it behind your back. When the reference count drops to zero, the memory is freed.</p><p>Python uses that safety to save memory. Short, identifier-like strings are often <em>interned</em> (stored once and reused):</p><pre>&gt;&gt;&gt; s1 = &quot;Best&quot;<br>&gt;&gt;&gt; s2 = &quot;Best&quot;<br>&gt;&gt;&gt; s1 is s2<br>True</pre><p>Only some strings get this treatment, so always compare strings with ==, never with is.</p><h3>Integer pre-allocation: NSMALLPOSINTS and NSMALLNEGINTS</h3><p>Small integers get a special optimisation. Look at this:</p><pre>&gt;&gt;&gt; a = 256<br>&gt;&gt;&gt; b = 256<br>&gt;&gt;&gt; a is b<br>True<br>&gt;&gt;&gt; a = int(&quot;257&quot;)<br>&gt;&gt;&gt; b = int(&quot;257&quot;)<br>&gt;&gt;&gt; a is b<br>False<br>&gt;&gt;&gt; a = int(&quot;-5&quot;)<br>&gt;&gt;&gt; b = int(&quot;-5&quot;)<br>&gt;&gt;&gt; a is b<br>True<br>&gt;&gt;&gt; a = int(&quot;-6&quot;)<br>&gt;&gt;&gt; b = int(&quot;-6&quot;)<br>&gt;&gt;&gt; a is b<br>False</pre><p>When CPython starts, it creates an array of integer objects ahead of time. The size of that array comes from two constants in its C source code:</p><pre>#define NSMALLPOSINTS  257   /* 0 to 256   */<br>#define NSMALLNEGINTS  5     /* -5 to -1   */</pre><p>That gives <strong>262 integers, from -5 to 256</strong>, created before your program runs a single line. (In recent CPython versions the constants are named _PY_NSMALLPOSINTS and _PY_NSMALLNEGINTS, but they work the same way.)</p><p><strong>How they are used:</strong> whenever CPython needs an int, it first checks whether the value is between -NSMALLNEGINTS and NSMALLPOSINTS - 1. If it is, CPython does not allocate anything. It returns a reference to the object already in the array and increases its reference count. Outside that range, a new object is created every time. That&#39;s why every 256 in your program is the same object, but two 257s built at run time are not:</p><pre>small_ints array (created at start-up)<br> ┌──────┬──────┬─────┬──────┬──────┬─────┬──────┐<br> │  -5  │  -4  │ ... │  0   │  1   │ ... │ 256  │<br> └──────┴──────┴─────┴──────┴──────┴─────┴──────┘<br>                        ▲                    ▲<br>               a = 0 ───┘     x = 256 ───────┤<br>                              y = 256 ───────┘   (x is y → True)</pre><p><strong>Why those values?</strong> Because they are the <strong>most used integers</strong> in real programs: 0 and 1 everywhere, loop counters and list indexes, small counts and lengths, every possible byte value (0 to 255), and small negatives like -1, which is a very common &quot;not found&quot; or &quot;last item&quot; value. Creating and destroying objects for these numbers millions of times would waste time and memory. Sharing them is safe <em>only because integers are immutable</em>.</p><p>(Inside a single script or line, the compiler may also reuse identical constants such as 257, so you can sometimes see True for bigger numbers too. Don&#39;t rely on it. Use == to compare numbers.)</p><h3>The special case of tuple and frozenset</h3><p>A tuple is immutable, but that only means <strong>the tuple’s own slots can’t be changed</strong>. Each slot holds a reference to an object, and if that object is mutable, it can still change:</p><pre>&gt;&gt;&gt; t = (1, [2, 3])<br>&gt;&gt;&gt; t[1].append(4)       # changing the list INSIDE the tuple: allowed<br>&gt;&gt;&gt; t<br>(1, [2, 3, 4])<br>&gt;&gt;&gt; t[1] = [9]           # changing which object the slot points to: not allowed<br>TypeError: &#39;tuple&#39; object does not support item assignment</pre><pre>┌───┐     ┌───────── tuple ─────────┐<br> │ t │────▶│ slot 0 │ slot 1         │   ← slots are fixed forever<br> └───┘     └───┬────┴───┬────────────┘<br>               ▼        ▼<br>          ┌───────┐  ┌───────────────┐<br>          │ int 1 │  │ list [2, 3, 4]│   ← this list can still change<br>          └───────┘  └───────────────┘</pre><p>One side effect: a tuple that contains a mutable object can’t be hashed, so it can’t be used as a dictionary key:</p><pre>&gt;&gt;&gt; hash((1, [2, 3]))<br>TypeError: unhashable type: &#39;list&#39;</pre><p>frozenset is the immutable version of set: you can&#39;t add or remove items. Its elements must be hashable, so it can&#39;t hold a list. It <em>can</em> hold instances of your own classes, though, and those objects can still change on the inside:</p><pre>&gt;&gt;&gt; frozenset([[1, 2]])<br>TypeError: unhashable type: &#39;list&#39;</pre><pre>&gt;&gt;&gt; class Box:<br>...     def __init__(self):<br>...         self.items = []<br>...<br>&gt;&gt;&gt; b = Box()<br>&gt;&gt;&gt; fs = frozenset([b])<br>&gt;&gt;&gt; b.items.append(&quot;x&quot;)    # the frozenset is unchanged, but b changed<br>&gt;&gt;&gt; b in fs, b.items<br>(True, [&#39;x&#39;])</pre><p>So “immutable” describes the container, not necessarily everything it contains.</p><h3>Why it matters: how Python treats mutable and immutable objects differently</h3><ul><li><strong>Aliases are only dangerous with mutable objects.</strong> If two names share an immutable object, neither can change it, so sharing is harmless. If they share a mutable object, a change through one name shows up through the other, which is a classic source of bugs.</li><li><strong>Only immutable (hashable) objects can be dictionary keys or set elements.</strong> Python relies on a key’s hash never changing. {(1, 2): &quot;ok&quot;} works; {[1, 2]: &quot;no&quot;} raises TypeError.</li><li><strong>Immutable objects can be shared and cached</strong> (small integers, interned strings, the single empty tuple: () is () is True). Mutable objects are always created fresh, because sharing them would be unsafe.</li><li><strong>“Changing” an immutable object costs a new object.</strong> Building a long string with s += &quot;x&quot; in a loop creates a new string each time; collecting pieces in a list and calling &quot;&quot;.join(...) once is the efficient way.</li><li><strong>If you want an independent copy of a mutable object, ask for one.</strong> Use l[:], list(l) or l.copy():</li></ul><pre>&gt;&gt;&gt; l = [1, 2, 3]<br>&gt;&gt;&gt; c = l[:]<br>&gt;&gt;&gt; c == l, c is l<br>(True, False)</pre><h3>How arguments are passed to functions</h3><p>Python doesn’t use “pass by value” or “pass by reference” as they exist in C. It uses <strong>pass by assignment</strong> (also called “pass by object reference”). When you call f(x), the parameter inside f becomes a new name for the <strong>same object</strong>, exactly as if Python ran param = x:</p><pre>&gt;&gt;&gt; def show(x):<br>...     return id(x)<br>...<br>&gt;&gt;&gt; v = [1]<br>&gt;&gt;&gt; show(v) == id(v)<br>True</pre><p>What happens next depends on the object.</p><p><strong>Immutable argument:</strong> the function can’t change the object. Something like n += 1 only moves the function&#39;s <em>local</em> name to a new object; the caller&#39;s variable is untouched.</p><pre>def increment(n):<br>    n += 1</pre><pre>a = 1<br>increment(a)<br>print(a)          # 1</pre><pre>caller            function increment<br> ┌───┐             ┌───┐<br> │ a │──┐          │ n │──┐    (n += 1 moves n to a new int 2;<br> └───┘  │          └───┘  │     a still refers to 1)<br>        ▼                 ▼<br>   ┌─────────┐       ┌─────────┐<br>   │  int 1  │       │  int 2  │<br>   └─────────┘       └─────────┘</pre><p><strong>Mutable argument:</strong> the function receives the same object, so changes made in place are visible to the caller:</p><pre>def increment(n):<br>    n.append(4)</pre><pre>l = [1, 2, 3]<br>increment(l)<br>print(l)          # [1, 2, 3, 4]</pre><p><strong>But rebinding the parameter never affects the caller</strong>, even for a mutable object, because it only moves the local name:</p><pre>def assign_value(n, v):<br>    n = v</pre><pre>l1 = [1, 2, 3]<br>l2 = [4, 5, 6]<br>assign_value(l1, l2)<br>print(l1)         # [1, 2, 3]</pre><p>Rule of thumb: a function can <em>modify</em> a mutable object you pass it, but it can never make <em>your variable</em> point to a different object. If a function shouldn’t change your list, pass it a copy (f(my_list[:])). If it needs to give you a new value, have it return it.</p><h3>Conclusion</h3><p>“Everything is an object” is not just a slogan. Names refer to objects, assignment creates aliases instead of copies, mutable objects change in place while immutable ones are replaced, and functions receive references to the very objects you pass in. With id(), type(), is and a quick memory sketch, you can predict what any of these snippets will print instead of guessing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=136cad3846ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>