<?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 sara rebati on Medium]]></title>
        <description><![CDATA[Stories by sara rebati on Medium]]></description>
        <link>https://medium.com/@sararebati94?source=rss-24ea61084af9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*XqdsnO2v9fMYAY5t</url>
            <title>Stories by sara rebati on Medium</title>
            <link>https://medium.com/@sararebati94?source=rss-24ea61084af9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 06:09:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sararebati94/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[What Happens When You Type https://www.google.com in Your Browser and Press Enter?]]></title>
            <link>https://medium.com/@sararebati94/what-happens-when-you-type-https-www-google-com-in-your-browser-and-press-enter-24e32d39a7e6?source=rss-24ea61084af9------2</link>
            <guid isPermaLink="false">https://medium.com/p/24e32d39a7e6</guid>
            <category><![CDATA[how-it-works]]></category>
            <category><![CDATA[network]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[servers]]></category>
            <dc:creator><![CDATA[sara rebati]]></dc:creator>
            <pubDate>Fri, 05 Jun 2026 16:52:44 GMT</pubDate>
            <atom:updated>2026-06-05T16:52:44.840Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ed4zTlth_CA4_1EzZuN09w.png" /></figure><h3>Introduction</h3><p>Every day, billions of people use the Internet without thinking about the complex infrastructure working behind the scenes.</p><p>Typing a simple URL such as:</p><pre>https://www.google.com</pre><p>and pressing <strong>Enter</strong> triggers dozens of operations involving DNS servers, routers, switches, firewalls, load balancers, web servers, application servers, databases, encryption protocols, and browser rendering engines.</p><p>Although this process takes only a few milliseconds, many different technologies work together to deliver a secure and reliable web experience.</p><p>In this article, we will follow the complete journey of a request from a user’s browser to Google’s infrastructure and back to the user’s screen.</p><h3>Step 1: URL Parsing</h3><p>The process begins when the user types:</p><pre>https://www.google.com</pre><p>The browser immediately analyzes the URL and separates it into several components.</p><p>ComponentValueProtocolHTTPSDomain Name<a href="http://www.google.com/">www.google.com</a>Port443Path/</p><p>The browser now knows that it must establish a secure HTTPS connection with Google’s servers.</p><p>However, it still does not know where Google is located on the Internet.</p><p>To communicate, it needs an IP address.</p><h3>Step 2: DNS Resolution</h3><p>Humans prefer domain names because they are easy to remember.</p><p>Computers communicate using IP addresses.</p><p>The browser must therefore translate:</p><pre>www.google.com</pre><p>into an IP address.</p><p>This process is called <strong>DNS Resolution</strong>.</p><p>DNS stands for:</p><pre>Domain Name System</pre><p>and acts like the phonebook of the Internet.</p><h3>Browser Cache</h3><p>The browser first checks its local DNS cache.</p><p>If the address was recently used, the browser may already know the corresponding IP address.</p><p>If no entry exists, the browser continues.</p><h3>Operating System Cache</h3><p>The operating system also maintains a DNS cache.</p><p>If the domain is found there, the process stops.</p><p>Otherwise, the request is sent to a DNS resolver.</p><h3>Recursive DNS Resolver</h3><p>The resolver is usually provided by:</p><ul><li>the Internet Service Provider (ISP)</li><li>Google DNS (8.8.8.8)</li><li>Cloudflare DNS (1.1.1.1)</li></ul><p>The resolver performs several queries.</p><h3>Root DNS Server</h3><p>The resolver contacts a Root DNS Server.</p><p>The root server does not know the IP address of Google, but it knows where to find the .com domain servers.</p><h3>Top-Level Domain Server</h3><p>The resolver then contacts the .com TLD server.</p><p>The TLD server knows which authoritative DNS server is responsible for Google.</p><h3>Authoritative DNS Server</h3><p>Finally, the resolver contacts Google’s authoritative DNS server.</p><p>The server returns an IP address.</p><p>Example:</p><pre>www.google.com → 142.250.x.x</pre><p>The resolver sends the result back to the browser.</p><p>Now the browser knows where to send the request.</p><h3>Step 3: TCP Connection</h3><p>Before exchanging data, a reliable connection must be established.</p><p>HTTPS relies on TCP.</p><p>TCP stands for:</p><pre>Transmission Control Protocol</pre><p>It guarantees:</p><ul><li>reliable delivery</li><li>ordered delivery</li><li>error detection</li></ul><p>To establish a TCP connection, the client and server perform a Three-Way Handshake.</p><h3>SYN</h3><p>The browser sends:</p><pre>SYN</pre><p>This means:</p><pre>&quot;I want to establish a connection.&quot;</pre><h3>SYN-ACK</h3><p>Google responds:</p><pre>SYN-ACK</pre><p>Meaning:</p><pre>&quot;I received your request and I agree.&quot;</pre><h3>ACK</h3><p>The browser responds:</p><pre>ACK</pre><p>Meaning:</p><pre>&quot;Connection established.&quot;</pre><p>The TCP session is now active.</p><h3>Step 4: TLS/SSL Handshake</h3><p>The website uses HTTPS.</p><p>HTTPS means:</p><pre>HTTP + TLS</pre><p>Before any HTTP data is exchanged, both sides must establish encrypted communication.</p><h3>Client Hello</h3><p>The browser sends a Client Hello message containing:</p><ul><li>supported TLS versions</li><li>supported cipher suites</li><li>random cryptographic values</li></ul><h3>Server Hello</h3><p>Google responds with:</p><pre>Server Hello</pre><p>and provides:</p><ul><li>selected cipher suite</li><li>TLS certificate</li><li>public key</li></ul><h3>Certificate Validation</h3><p>The browser validates:</p><ul><li>Certificate Authority</li><li>Expiration Date</li><li>Domain Name</li></ul><p>If the certificate is trusted, communication continues.</p><h3>Session Key Generation</h3><p>Both sides generate shared encryption keys.</p><p>From this moment:</p><pre>Client ↔ Google</pre><p>communication becomes encrypted.</p><p>Nobody can read the exchanged data without the encryption key.</p><h3>Step 5: Firewall Inspection</h3><p>The encrypted request reaches Google’s infrastructure.</p><p>Before accessing any server, traffic passes through firewalls.</p><p>A firewall is a security device that filters incoming and outgoing traffic according to predefined rules.</p><p>Its objectives are:</p><ul><li>blocking malicious traffic</li><li>preventing unauthorized access</li><li>protecting infrastructure</li><li>limiting attacks</li></ul><p>Only authorized HTTPS traffic on port 443 is allowed.</p><h3>Step 6: Load Balancing</h3><p>Google receives billions of requests every day.</p><p>A single server could never handle this amount of traffic.</p><p>Therefore, the request reaches a Load Balancer.</p><p>The Load Balancer distributes traffic among multiple servers.</p><p>Benefits include:</p><ul><li>scalability</li><li>fault tolerance</li><li>high availability</li><li>improved performance</li></ul><p>Algorithms may include:</p><ul><li>Round Robin</li><li>Least Connections</li><li>Weighted Routing</li></ul><p>The load balancer selects one backend server.</p><h3>Step 7: Web Server Processing</h3><p>The selected backend server receives the request.</p><p>Typically, a web server such as:</p><pre>Nginx<br>Apache</pre><p>is responsible for handling HTTP requests.</p><p>The web server can:</p><ul><li>serve static files</li><li>manage HTTPS</li><li>cache content</li><li>act as a reverse proxy</li></ul><p>If dynamic content is required, the request is forwarded to the application server.</p><h3>Step 8: Application Server Processing</h3><p>The application server contains the business logic of the application.</p><p>Examples include:</p><ul><li>Python</li><li>Node.js</li><li>Java</li><li>PHP</li><li>Go</li></ul><p>The application server performs tasks such as:</p><ul><li>authentication</li><li>personalization</li><li>session management</li><li>data processing</li></ul><p>To complete the request, it often needs data stored in a database.</p><h3>Step 9: Database Query</h3><p>The application server sends queries to a database.</p><p>Databases store information such as:</p><ul><li>user accounts</li><li>search indexes</li><li>preferences</li><li>sessions</li><li>analytics</li></ul><p>Example:</p><pre>SELECT *<br>FROM users<br>WHERE id = 123;</pre><p>The database executes the query and returns the requested data.</p><h3>Step 10: Response Generation</h3><p>The application server now has everything needed to build the response.</p><p>It generates:</p><ul><li>HTML</li><li>CSS</li><li>JavaScript</li><li>JSON</li></ul><p>The response is sent back to the web server.</p><p>The web server returns it through the encrypted HTTPS connection.</p><h3>Step 11: Browser Rendering</h3><p>The browser receives the response.</p><p>It performs several operations:</p><h3>Parse HTML</h3><p>Builds the DOM tree.</p><h3>Download CSS</h3><p>Applies styling.</p><h3>Execute JavaScript</h3><p>Creates dynamic behavior.</p><h3>Build Render Tree</h3><p>Combines DOM and CSSOM.</p><h3>Paint Pixels</h3><p>Displays the page on the screen.</p><p>The user finally sees Google’s homepage.</p><h3>Conclusion</h3><p>Typing a URL and pressing Enter appears simple, but dozens of systems collaborate to deliver the requested page.</p><p>The complete journey involves:</p><ul><li>DNS Resolution</li><li>TCP/IP Networking</li><li>TLS Encryption</li><li>Firewalls</li><li>Load Balancers</li><li>Web Servers</li><li>Application Servers</li><li>Databases</li><li>Browser Rendering</li></ul><p>Understanding this process is fundamental for Software Engineers, DevOps Engineers, System Administrators, and Site Reliability Engineers because it demonstrates how modern web applications operate at scale.</p><h3>Infrastructure Diagram Overview</h3><p>The following diagram illustrates the complete journey of a web request after a user types <a href="https://www.google.com/"><strong>https://www.google.com</strong></a> into a browser and presses <strong>Enter</strong>.</p><p>It provides a high-level view of the different infrastructure components involved in delivering a web page, from DNS resolution to browser rendering. The diagram highlights how the request is translated into an IP address, secured through TLS/SSL encryption, filtered by a firewall, distributed by a load balancer, processed by web and application servers, and finally served back to the user after retrieving the necessary data from the database.</p><p>Understanding this workflow helps visualize how modern web applications achieve security, scalability, reliability, and performance while handling millions of requests every day.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SLgQOrMXjnBI-12nJL5T5w.png" /><figcaption>What happens when you type google.com in your browser and press Enter</figcaption></figure><h3>Diagram Description</h3><ol><li>The user enters <a href="https://www.google.com/"><strong>https://www.google.com</strong></a> in the browser.</li><li>A <strong>DNS query</strong> resolves the domain name into an IP address.</li><li>A <strong>TCP connection</strong> is established through the Three-Way Handshake.</li><li>A <strong>TLS/SSL handshake</strong> secures the communication channel.</li><li>The request passes through a <strong>firewall</strong> that filters incoming traffic.</li><li>A <strong>load balancer</strong> distributes the request to an available web server.</li><li>The <strong>web server</strong> receives the request and forwards dynamic operations to the application server.</li><li>The <strong>application server</strong> executes the business logic and requests data from the database.</li><li>The <strong>database</strong> returns the required information.</li><li>The application server generates the response and sends it back through the web server and load balancer.</li><li>The browser receives the encrypted response, renders the page, and displays the final content to the user.</li></ol><p>This architecture demonstrates the interaction between networking, security, application processing, and data storage layers that make modern web services possible.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24e32d39a7e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python: Mutable, Immutable… Everything is Object!]]></title>
            <link>https://medium.com/@sararebati94/python-mutable-immutable-everything-is-object-6cad9d9b3b64?source=rss-24ea61084af9------2</link>
            <guid isPermaLink="false">https://medium.com/p/6cad9d9b3b64</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python-object]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[sara rebati]]></dc:creator>
            <pubDate>Mon, 30 Mar 2026 13:16:42 GMT</pubDate>
            <atom:updated>2026-03-30T14:27:45.441Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YDWJwEGQArG92_cELFkhqg.png" /></figure><h3>Introduction</h3><p>If you have been writing Python for a while, you have probably run into a moment where a variable changed its value without you ever touching it — or the opposite, where you expected a change and nothing happened. These mysteries come down to one fundamental truth about Python: <strong>everything is an object</strong>.</p><p>Unlike some languages where variables are boxes that <em>hold</em> values, Python variables are more like <strong>labels stuck on objects</strong>. When you write a = 42, Python creates an integer object with the value 42 somewhere in memory, and sticks the label a on it. When you write b = a, you are not copying the value — you are sticking a second label on the <em>same object</em>.</p><p>Understanding this mental model is one of the most important steps to writing correct, predictable Python code. In this post we will cover:</p><ul><li>How id() and type() let you X-ray any object</li><li>The difference between mutable and immutable types</li><li>How CPython pre-allocates integers using NSMALLPOSINTS and NSMALLNEGINTS</li><li>The alias mechanism and why it causes so many bugs</li><li>The special case of tuples and frozen sets</li><li>How Python passes arguments to functions, and what that implies</li></ul><p>By the end, the two snippets below will hold no more mysteries for you:</p><p>python</p><pre># Why doesn&#39;t b change?<br>&gt;&gt;&gt; a = 1<br>&gt;&gt;&gt; b = a<br>&gt;&gt;&gt; a = 2<br>&gt;&gt;&gt; b<br>1</pre><pre># Why DOES m change?<br>&gt;&gt;&gt; l = [1, 2, 3]<br>&gt;&gt;&gt; m = l<br>&gt;&gt;&gt; l[0] = &#39;x&#39;<br>&gt;&gt;&gt; m<br>[&#39;x&#39;, 2, 3]</pre><h3>id() and type() — X-raying any object</h3><p>Every object in Python has three characteristics:</p><p>CharacteristicHow to read itWhat it tells you<strong>Identity</strong>id(obj)Unique memory address (an integer)<strong>Type</strong>type(obj)The class the object belongs to<strong>Value</strong>print(obj)The content</p><p>python</p><pre>x = 42<br>print(id(x))    # e.g. 140245534788432  ← memory address<br>print(type(x))  # &lt;class &#39;int&#39;&gt;<br>print(x)        # 42</pre><pre>RAM (heap)<br>┌────────────────────────────────┐<br>│  Address : 140245534788432     │  ◄── id(x)<br>│  Type    : int                 │  ◄── type(x)<br>│  Value   : 42                  │  ◄── x<br>└────────────────────────────────┘<br>          ▲<br>          │  reference<br>          │<br>       x = 42<br>   (the variable is just a label)</pre><p>The key insight: id() lets us check whether two variables point to the <strong>same object in memory</strong>, or merely to two objects that happen to have the same value. This is the difference between is and ==:</p><p>python</p><pre>a = [1, 2, 3]<br>b = [1, 2, 3]   # a new list, created separately</pre><pre>print(a == b)   # True  → same content<br>print(a is b)   # False → different objects (different id)<br>print(id(a))    # e.g. 140245530001234<br>print(id(b))    # e.g. 140245527654321  ← different!</pre><blockquote><strong><em>Rule:</em></strong><em> </em><em>== compares </em><strong><em>values</em></strong><em>. </em><em>is compares </em><strong><em>identities</em></strong><em> (memory addresses via </em><em>id()).</em></blockquote><h3>Immutable Objects — set in stone</h3><p>An <strong>immutable</strong> object is one whose value <strong>cannot be changed after it is created</strong>. The built-in immutable types in Python are:</p><pre>int, float, complex   ← numbers<br>str                   ← strings<br>bool                  ← True / False<br>bytes                 ← byte sequences<br>tuple                 ← ordered, immutable sequences<br>frozenset             ← immutable version of set</pre><p>When you “modify” an immutable variable, Python actually <strong>creates a brand-new object</strong> and redirects the label to it. The original object stays untouched.</p><p>python</p><pre>a = &quot;cat&quot;<br>print(id(a))    # e.g. 140245534000001</pre><pre>a = &quot;dog&quot;       # not a modification — a NEW str object is created<br>print(id(a))    # e.g. 140245534000999  ← different id!</pre><pre>BEFORE:   a ──► [&quot;cat&quot;]   id = 0xAAA</pre><pre>a = &quot;dog&quot; creates a NEW object:<br>AFTER:    a ────────────────► [&quot;dog&quot;]   id = 0xBBB<br>          (the &quot;cat&quot; object is abandoned)</pre><h3>How immutable objects are stored in memory</h3><p>Because immutable objects can never change, Python can safely <strong>reuse</strong> them. When CPython creates an immutable object, it stores it on the heap. If the same value is needed again, Python may return the <strong>existing object</strong> rather than allocating a new one — this optimization is called <strong>interning</strong>.</p><pre>Heap memory for immutable int objects:</pre><pre>┌────────────────────────────────────┐<br>│  [int: 0]   id = 0x7f001   ◄── a  │<br>│  [int: 1]   id = 0x7f002   ◄── b  │<br>│  [int: 2]   id = 0x7f003          │<br>│  ...                               │<br>│  [int: 256] id = 0x7f103          │<br>└────────────────────────────────────┘<br>    These 262 objects are created ONCE<br>    at CPython startup and reused forever.</pre><h3>CPython Integer Pre-allocation: NSMALLPOSINTS and NSMALLNEGINTS</h3><p>This is one of the most important implementation details of CPython. When the interpreter starts, it <strong>pre-allocates a fixed array of integer objects</strong> before any user code runs. These objects are defined by two constants in CPython’s source code (Objects/longobject.c):</p><p>c</p><pre>#define NSMALLPOSINTS  257   /* integers 0 to 256  */<br>#define NSMALLNEGINTS  5     /* integers -5 to -1  */</pre><p>Together, they cover every integer from <strong>-5 to 256</strong> — a total of <strong>262 pre-created integer objects</strong>.</p><h3>How NSMALLPOSINTS and NSMALLNEGINTS are used</h3><p>Every time CPython needs an integer value in that range, it does <strong>not</strong> allocate a new object. Instead, it looks up the pre-existing object in the array and returns a reference to it. This is why:</p><p>python</p><pre>a = 42<br>b = 42<br>print(a is b)           # True  ← same pre-allocated object<br>print(id(a) == id(b))   # True</pre><pre>a = 300<br>b = 300<br>print(a is b)           # False ← outside the range, two new objects</pre><pre>CPython startup — integer cache array:</pre><pre>index  value   object id<br>  0    -5      0x7f001   ◄── any variable set to -5 gets this<br>  1    -4      0x7f002<br>  2    -3      0x7f003<br>  3    -2      0x7f004<br>  4    -1      0x7f005<br>  5     0      0x7f006<br>  6     1      0x7f007<br>  ...<br>261   256      0x7f103   ◄── any variable set to 256 gets this</pre><pre>Above 256 or below -5 → CPython allocates a fresh object each time.</pre><h3>Why these specific values?</h3><p>The values of NSMALLPOSINTS (257, covering 0–256) and NSMALLNEGINTS (5, covering -5–-1) were chosen because <strong>these are the integers programmers use most often</strong> in real-world code:</p><ul><li><strong>0 to 256</strong>: loop counters, array indices, ASCII character codes, small counts — these appear constantly in everyday Python programs.</li><li><strong>-5 to -1</strong>: negative indices (list[-1], list[-2]…), small negative offsets — also extremely common.</li></ul><p>Pre-allocating these 262 objects saves memory (no duplicate objects) and speeds up code (no allocation overhead for the most common values).</p><blockquote><strong><em>Practical consequence:</em></strong><em> Never use </em><em>is to compare integers you expect to be equal. The behavior is only </em>guaranteed<em> for -5 to 256. Outside that range, two variables holding the same value may or may not share an object, depending on the context.</em></blockquote><p>python</p><pre># SAFE<br>print(42 == 42)      # True  ← always correct</pre><pre># RISKY<br>print(42 is 42)      # True  only because 42 is cached<br>print(300 is 300)    # True  in the REPL (same literal optimized)<br>                     # but NOT guaranteed in all contexts!</pre><h3>Mutable Objects — living, breathing data</h3><p>A <strong>mutable</strong> object can be modified <strong>in place</strong>, without creating a new object. The built-in mutable types are:</p><pre>list        ← ordered, modifiable sequences<br>dict        ← key-value mappings<br>set         ← unordered collections of unique values<br>bytearray   ← mutable byte sequences</pre><p>When you modify a mutable object, the object <strong>stays at the same memory address</strong> — only its content changes.</p><p>python</p><pre>l = [1, 2, 3]<br>print(id(l))    # e.g. 140245530001234</pre><pre>l[0] = 99       # in-place modification<br>print(id(l))    # e.g. 140245530001234  ← same id!<br>print(l)        # [99, 2, 3]</pre><pre>BEFORE:   l ──► [1, 2, 3]   id = 0xAAA</pre><pre>l[0] = 99  (mutation — same object):<br>AFTER:    l ──► [99, 2, 3]  id = 0xAAA  ← unchanged id</pre><h3>Assignment and Referencing — what really happens</h3><h3>Assignment</h3><p>When you write a = 42, Python does <strong>not</strong> store 42 inside a. Instead:</p><ol><li>It creates (or finds) an integer object with value 42 in memory.</li><li>It binds the name a to that object — a is a <strong>reference</strong> (a label).</li></ol><p>python</p><pre>a = 42          # a → object(42)<br>b = &quot;hello&quot;     # b → object(&quot;hello&quot;)<br>c = [1, 2, 3]   # c → object([1, 2, 3])</pre><h3>Referencing (creating aliases)</h3><p>When you write b = a, you are <strong>not</strong> copying the object. You are creating a second reference to the <strong>same object</strong>:</p><p>python</p><pre>a = [1, 2, 3]<br>b = a           # b is a reference to the same object as a</pre><pre>print(id(a) == id(b))   # True<br>print(a is b)           # True</pre><pre>a = [1, 2, 3]  →   a ──┐<br>                         ▼<br>                   [1, 2, 3]   id = 0xAAA   ← ONE object<br>                         ▲<br>b = a          →   b ──┘</pre><p>This is what a <strong>reference</strong> looks like in memory: two labels, one object.</p><h3>The Alias Mechanism — the most common source of bugs</h3><p>An <strong>alias</strong> is when two (or more) variables reference the <strong>same object</strong> in memory. For immutable types, aliases are harmless — you cannot change the object anyway. For <strong>mutable</strong> types, an alias means that a change made through one variable is immediately visible through all others.</p><p>python</p><pre># Alias with a mutable object<br>l1 = [1, 2, 3]<br>l2 = l1             # l2 is an ALIAS of l1</pre><pre>l1.append(4)<br>print(l2)           # [1, 2, 3, 4]  ← l2 changed!<br>print(l1 is l2)     # True</pre><pre>l1 = [1, 2, 3]  →   l1 ──┐<br>                           ▼<br>                     [1, 2, 3]   id = 0xAAA<br>                           ▲<br>l2 = l1         →   l2 ──┘   ← ALIAS</pre><pre>l1.append(4) mutates the shared object:</pre><pre>l1 ──┐<br>      ▼<br>[1, 2, 3, 4]   id = 0xAAA   ← SAME object, modified<br>      ▲<br>l2 ──┘</pre><pre>→ Both l1 and l2 now show [1, 2, 3, 4]</pre><p>This is the mystery from Snippet B in the introduction — now fully explained.</p><h3>Breaking an alias — cloning a list</h3><p>To get a truly <strong>independent copy</strong>, use one of these:</p><p>python</p><pre>original = [1, 2, 3]<br>clone1 = original[:]          # slice — most concise<br>clone2 = list(original)       # constructor<br>clone3 = original.copy()      # method</pre><pre>original[0] = 99<br>print(original)     # [99, 2, 3]<br>print(clone1)       # [1, 2, 3]  ← independent!<br>print(clone1 is original)   # False ← different objects<br>print(clone1 == original)   # False ← different values now</pre><blockquote><em>⚠️ </em><strong><em>Shallow vs deep copy:</em></strong><em> </em><em>[:] creates a </em>shallow copy<em> — the list is new, but if it contains nested mutable objects (lists inside lists), those inner objects are </em><strong><em>still shared</em></strong><em>. Use </em><em>copy.deepcopy() for a fully independent clone.</em></blockquote><p>python</p><pre>import copy</pre><pre>nested = [[1, 2], [3, 4]]<br>shallow = nested[:]<br>deep = copy.deepcopy(nested)</pre><pre>nested[0].append(99)<br>print(shallow)   # [[1, 2, 99], [3, 4]]  ← inner list shared!<br>print(deep)      # [[1, 2], [3, 4]]      ← fully independent</pre><h3>The Special Case of Tuples and Frozen Sets</h3><p>Tuples and frozen sets are <strong>immutable</strong> — you cannot add, remove, or replace their elements. However, they are containers, and the objects <em>inside</em> them can be mutable.</p><h3>Tuples containing mutable objects</h3><p>python</p><pre>t = ([1, 2], &quot;hello&quot;)</pre><pre># This would raise a TypeError:<br># t[0] = [9, 9]   ← cannot reassign tuple element</pre><pre># But this works!<br>t[0].append(3)          # we are mutating the LIST inside the tuple<br>print(t)                # ([1, 2, 3], &#39;hello&#39;)</pre><pre>t = ( ref_A,  ref_B )<br>       ↓         ↓<br>  [1, 2]    &quot;hello&quot;</pre><pre>t[0] = [9, 9]   → ❌ TypeError: the TUPLE reference cannot change<br>t[0].append(3)  → ✅ the LIST object at ref_A is mutated</pre><pre>After mutation:<br>t = ( ref_A,  ref_B )   ← the tuple itself is unchanged (same refs)<br>       ↓         ↓<br>  [1, 2, 3]  &quot;hello&quot;    ← the list object changed</pre><p>The tuple is technically unchanged (its references are the same). The <strong>object it points to</strong> has changed. This is why a tuple can be considered “immutable but potentially changing.”</p><h3>Why this matters for hashing</h3><p>Because tuples <em>might</em> contain mutable objects, Python cannot always use them as dictionary keys or set members:</p><p>python</p><pre>t1 = (1, 2, 3)      # hashable → can be a dict key ✅<br>t2 = ([1, 2], 3)    # NOT hashable → contains a list ❌</pre><pre>d = {}<br>d[t1] = &quot;ok&quot;       # works<br>d[t2] = &quot;fail&quot;     # TypeError: unhashable type: &#39;list&#39;</pre><h3>Frozen sets</h3><p>A frozenset is the immutable equivalent of set. It <strong>cannot</strong> contain mutable objects (since all its elements must be hashable), so this issue does not arise:</p><p>python</p><pre>fs = frozenset([1, 2, 3])   # immutable and hashable ✅<br># frozenset([[1, 2], 3])    # TypeError: unhashable type: &#39;list&#39; ❌</pre><h3>Why Does It Matter? Mutability in practice</h3><h3>+ vs += on lists — a critical difference</h3><p>python</p><pre>l = [1, 2, 3]<br>m = l               # alias</pre><pre>l = l + [4]         # l + [4] creates a NEW list, then l is rebound<br>print(m)            # [1, 2, 3]  ← m still points to the old object</pre><pre>l = [1, 2, 3]<br>m = l               # alias again</pre><pre>l += [4]            # += on a list calls list.__iadd__ → mutates in place<br>print(m)            # [1, 2, 3, 4]  ← m is affected!<br>print(l is m)       # True ← same object</pre><pre>l = l + [4]:                       l += [4]:<br>  l ──► [1,2,3,4] id=0xBBB (new)    l ──► [1,2,3,4] id=0xAAA (same)<br>  m ──► [1,2,3]   id=0xAAA          m ──► [1,2,3,4] id=0xAAA</pre><h3>How Arguments Are Passed to Functions</h3><p>Python uses a model called <strong>“pass by object reference”</strong> (also called “pass by assignment”). When you call a function:</p><ol><li>A new local variable (the parameter) is created.</li><li>That variable is <strong>assigned</strong> to the same object as the argument — it is an alias.</li></ol><p>Whether the original is affected depends on <strong>what you do with the alias</strong> inside the function.</p><h3>Immutable argument — no side effects</h3><p>python</p><pre>def increment(n):<br>    n += 1   # n = n + 1 → new int object, local rebinding only</pre><pre>a = 1<br>increment(a)<br>print(a)    # 1 ← unchanged</pre><pre>Before call:  a ──► [int: 1]   id = 0xAAA</pre><pre>Inside function:<br>  n = a  →  n ──► [int: 1]   id = 0xAAA  (alias)<br>  n += 1 →  n ──► [int: 2]   id = 0xBBB  (new object, n rebound locally)</pre><pre>After call:   a ──► [int: 1]   id = 0xAAA  ← unchanged</pre><h3>Mutable argument — side effects via mutation</h3><p>python</p><pre>def add_item(lst):<br>    lst.append(4)   # mutates the shared object</pre><pre>l = [1, 2, 3]<br>add_item(l)<br>print(l)    # [1, 2, 3, 4] ← modified!</pre><pre>Before call:  l ──► [1, 2, 3]   id = 0xAAA</pre><pre>Inside function:<br>  lst = l  →  lst ──► [1, 2, 3]   id = 0xAAA  (alias)<br>  lst.append(4)  →  [1, 2, 3, 4]  id = 0xAAA  (same object, mutated)</pre><pre>After call:   l ──► [1, 2, 3, 4]   id = 0xAAA  ← modified!</pre><h3>Reassignment — never affects the original</h3><p>Reassigning a parameter (pointing it to a <em>different</em> object) <strong>never</strong> modifies the original, regardless of type:</p><p>python</p><pre>def reassign(n, v):<br>    n = v   # local label only — does not touch the original</pre><pre>l1 = [1, 2, 3]<br>l2 = [4, 5, 6]<br>reassign(l1, l2)<br>print(l1)   # [1, 2, 3]  ← unchanged!</pre><h3>Summary</h3><p>SituationOriginal modified?Immutable argument, any operation❌ NeverMutable argument + mutation (.append, [i]=x, .update…)✅ YesMutable argument + reassignment (n = something)❌ Nol = l + [x]❌ New object createdl += [x] on a list✅ Mutated in place</p><h3>Conclusion</h3><p>Python’s “everything is an object” philosophy is elegant, but it comes with rules that can catch you off guard. Here is what to carry with you:</p><ol><li><strong>Every value is an object</strong> with an identity (id()), a type (type()), and a value.</li><li><strong>== checks values. </strong><strong>is checks identity.</strong> Never use is to compare values.</li><li><strong>Immutable types</strong> (int, float, complex, str, bool, bytes, tuple, frozenset) create a new object on every modification.</li><li><strong>CPython pre-allocates 262 integer objects</strong> at startup (from -5 to 256) using NSMALLPOSINTS = 257 and NSMALLNEGINTS = 5. These cover the most commonly used integers in real code.</li><li><strong>Mutable types</strong> (list, dict, set, bytearray) are modified in place. Aliases share the same object — a mutation through one label affects all of them.</li><li><strong>Tuples and frozen sets are immutable containers</strong>, but a tuple that contains a mutable object (like a list) allows that inner object to be mutated — the tuple’s references stay the same, the pointed-to object changes.</li><li><strong>l = l + [x]</strong> creates a new object. <strong>l += [x]</strong> mutates the existing list in place.</li><li><strong>Function arguments</strong> receive a reference to the same object. Immutable arguments cannot produce side effects. Mutable ones can — through mutation, not reassignment.</li></ol><p>Master these rules, and Python’s behavior will never surprise you again.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6cad9d9b3b64" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>