<?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 Paola Suárez on Medium]]></title>
        <description><![CDATA[Stories by Paola Suárez on Medium]]></description>
        <link>https://medium.com/@paolasuarez?source=rss-a24484b6d9d3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*2I2TMMZbZeIwR2iit_4OCw.jpeg</url>
            <title>Stories by Paola Suárez on Medium</title>
            <link>https://medium.com/@paolasuarez?source=rss-a24484b6d9d3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 20:21:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@paolasuarez/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[Immutable and Mutable objects in Python, why does it matter?]]></title>
            <link>https://medium.com/@paolasuarez/immutable-and-mutable-objects-in-python-why-does-it-matter-fe5ba3b83932?source=rss-a24484b6d9d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe5ba3b83932</guid>
            <category><![CDATA[mutable-objects]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[immutable-objects]]></category>
            <category><![CDATA[variables-in-python]]></category>
            <dc:creator><![CDATA[Paola Suárez]]></dc:creator>
            <pubDate>Fri, 14 Oct 2022 23:06:07 GMT</pubDate>
            <atom:updated>2022-10-14T23:06:07.612Z</atom:updated>
            <content:encoded><![CDATA[<p>Beginner-friendly</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*c5nOE6S4UIby46aizoY1TQ.jpeg" /><figcaption><strong>Photo by </strong><a href="https://thegeekswatch.blogspot.com/2016/09/a-list-of-awesome-python-modules.html">thegeekswatch.blogspot.com</a></figcaption></figure><p>Python is considered a high-level programming language and everything is an object within.</p><p>After you understand objects, classes, and beyond, it is time to look a little bit closer at how Python works with different types of objects.</p><p>Have you ever modified a variable without knowing it or wanting to?</p><p>I mean:</p><blockquote>&gt;&gt;&gt; a = 1<br>&gt;&gt;&gt; b = a<br>&gt;&gt;&gt; a = 2<br>&gt;&gt;&gt; b<br>1</blockquote><p>Everything is all right. But what about this?</p><blockquote>&gt;&gt;&gt; list = [1, 2, 3]<br>&gt;&gt;&gt; my_list = list<br>&gt;&gt;&gt; list[0] = ‘x’<br>&gt;&gt;&gt; my_list<br>[‘x’, 2, 3]</blockquote><p>What??</p><p>To understand what is going on in our last example we need to know some information first.</p><p>Information like, what would you use to print the object type? (to understand what type we are dealing with)</p><p>Pretty simple, we use <strong>type()</strong>. Python type() is a built-in function that returns the type of the objects/data elements stored in any data type or returns a new type object depending on the arguments passed to the function. The Python type() function prints what type of data structures are used to store the data elements in a program.</p><p>Nice…</p><p>Now, how do you get the variable identifier (which is the memory address in the CPython implementation)?</p><p><strong>id()</strong></p><p>Pretty simple too. Python id() function returns the “identity” of the object.</p><p>How about if now you test your skills and let’s find out how many correct answers you can get:</p><blockquote>In the following code, do a and b point to the same object?<br>Yes or No.<br>&gt;&gt;&gt; a = 89<br>&gt;&gt;&gt; b = 100</blockquote><p>Answer: No, you can use id(a) and id(b) to double check</p><blockquote>In the following code, do a and b point to the same object?<br>Yes or No.<br>&gt;&gt;&gt; a = 89<br>&gt;&gt;&gt; b = 89</blockquote><p>Answer: Yes, python doesn’t waste any space.</p><blockquote>In the following code, do a and b point to the same object?<br>Yes or No.<br>&gt;&gt;&gt; a = 89<br>&gt;&gt;&gt; b = a</blockquote><p>Answer: yes, obviously.</p><blockquote>In the following code, do a and b point to the same object?<br>Yes or No.<br>&gt;&gt;&gt; a = 89<br>&gt;&gt;&gt; b = a + 1</blockquote><p>Answer: No, adding 1 is not the same.</p><blockquote>What do these 3 lines print?<br>True or False.<br>&gt;&gt;&gt; string1 = “Hello”<br>&gt;&gt;&gt; string2 = s1<br>&gt;&gt;&gt; print(string1 == string2)</blockquote><p>Answer: True. Remember that the “==” operator compares the value or equality of two objects.</p><blockquote>What do these 3 lines print?<br>True or False.<br>&gt;&gt;&gt; string1 = “Hello”<br>&gt;&gt;&gt; string2 = string1<br>&gt;&gt;&gt; print(string1 is string2)</blockquote><p>Answer: True. The “is” keyword is used to test if two variables refer to the same object. The test returns True if the two objects are the same object. The test returns False if they are not the same object.</p><blockquote>What do these 3 lines print?<br>True or False.<br>&gt;&gt;&gt; string1 = “Python”<br>&gt;&gt;&gt; string2 = “Python”<br>&gt;&gt;&gt; print(string1 == string2)</blockquote><p>Answer: True.</p><blockquote>What do these 3 lines print?<br>&gt;&gt;&gt; string1 = “Python”<br>&gt;&gt;&gt; string2 = “Python”<br>&gt;&gt;&gt; print(string1 is string2)</blockquote><p>Answer: True.</p><p>Strings understood. Now let’s see what happens with lists.</p><blockquote>What do these 3 lines print?<br>&gt;&gt;&gt; list1 = [1, 2, 3]<br>&gt;&gt;&gt; list2 = [1, 2, 3]<br>&gt;&gt;&gt; print(list1 == list2)</blockquote><p>Answer: True. Nothing strange so far.</p><blockquote>What do these 3 lines print?<br>&gt;&gt;&gt; list1 = [1, 2, 3]<br>&gt;&gt;&gt; list2 = [1, 2, 3]<br>&gt;&gt;&gt; print(list1 is list2)</blockquote><p>Answer: False. They are not the same object. It’s because lists are mutable, which means they can be modified, e.g. by my_list.append() or my_list.pop(), while strings can’t.<br>Is it important? Yes! if you don’t consider this you may hit a wall because everything seems so logical but your code won’t work. Watch <a href="https://www.youtube.com/watch?v=xwPWcFKeIac">this video</a> to understand more.</p><blockquote>What do these 3 lines print?<br>&gt;&gt;&gt; list1 = [1, 2, 3]<br>&gt;&gt;&gt; list2 = list1<br>&gt;&gt;&gt; print(list1 == list2)</blockquote><p>Answer: True</p><blockquote>What do these 3 lines print?<br>&gt;&gt;&gt; list1 = [1, 2, 3]<br>&gt;&gt;&gt; list2 = list1<br>&gt;&gt;&gt; print(list1 is list2)</blockquote><p>Answer: True, again.</p><blockquote>What does this script print?<br>list1 = [1, 2, 3]<br>list2 = list1<br>list1 = [1, 2, 3]<br>list2 = list1<br>list1.append(4)<br>print(list2)</blockquote><p>Answer: [1, 2, 3, 4]. They are pointing to the same object. Every time one of them changes the other will change too.</p><blockquote>What does this script print?<br>list1 = [1, 2, 3]<br>list2 = list1<br>list1 = list1 + [4]<br>print(list2)</blockquote><p>Answer: [1, 2, 3]. In this example, we are not modifying list1.</p><blockquote>What does this script print?<br>def increment(n):<br> n += 1</blockquote><blockquote>a = 1<br>increment(a)<br>print(a)</blockquote><p>Answer: 1. We will talk about this later.</p><blockquote>What does this script print?<br>def increment(n):<br> n.append(4)</blockquote><blockquote>list = [1, 2, 3]<br>increment(list)<br>print(list)</blockquote><p>Answer: [1, 2, 3, 4]</p><p>Let’s start with list assignation now.</p><blockquote>What does this script print?<br>def assign_value(a, b):<br> a = b</blockquote><blockquote>list1 = [1, 2, 3]<br>list2 = [4, 5, 6]<br>assign_value(list1, list2)<br>print(list1)</blockquote><p>Answer: [1, 2, 3]</p><blockquote>What about if we want to copy a list?<br>def copy_list(l):<br> return l[:]</blockquote><p>Otherwise, it won’t be a copy.</p><p>It is time for tuples:</p><blockquote>Are you sure you know what a tuple is? Let’s find out.<br>a = ()<br>Is “a” a tuple?</blockquote><p>Answer: Yes</p><blockquote>How about this one?<br>a = (1, 2)</blockquote><p>Answer: Of course yes</p><blockquote>And this one?<br>a = (1)</blockquote><p>Answer: no</p><blockquote>The next one:<br>a = (1, )</blockquote><p>Answer: Yes</p><blockquote>What does this script print?<br>a = (1)<br>b = (1)<br>a is b</blockquote><p>Answer: True</p><blockquote>What does this script print?<br>a = (1, 2)<br>b = (1, 2)<br>a is b</blockquote><p>Answer: False. Tuples are treated differently. Keep reading, you will find out why.</p><blockquote>What does this script print?<br>a = ()<br>b = ()<br>a is b</blockquote><p>Answer: True</p><p>Last questions:</p><blockquote>&gt;&gt;&gt; id(a)<br>139926795932424<br>&gt;&gt;&gt; a<br>[1, 2, 3, 4]<br>&gt;&gt;&gt; a = a + [5]<br>&gt;&gt;&gt; id(a)<br>Will the last line of this script print 139926795932424?</blockquote><p>Answer: No. It is not the same “a” from the beginning.</p><blockquote>&gt;&gt;&gt; a<br>[1, 2, 3]<br>&gt;&gt;&gt; id (a)<br>139926795932424<br>&gt;&gt;&gt; a += [4]<br>&gt;&gt;&gt; id(a)<br>Will the last line of this script print 139926795932424?</blockquote><p>Answer: Yes</p><h3>Mutable and Immutable Objects</h3><p>We called mutable objects to those that can be changed without altering the id. Most objects fit into this category, including user-made classes, list, dictionary, set, and byte array.</p><p>Mutable objects may lead to some unpredictable behavior, especially when it comes to creating aliases of variables. This means that two variables refer to the same object and have the same id. For example, a pet can be called by his formal name or a nickname or alias. We saw examples above where a change in one will also change the other.</p><p>When using the form b = b + element, a new instance of the same type is created. On the other hand, the addition with the += operator tries to use the least objects possible, so it adds the new element in place. This means a new instance is not created.</p><p>Other objects, such as numbers (e.g. integers, floats, complex numbers), tuples, frozen sets, bytes, and strings, are immutable objects. This means that the value of the object cannot change without changing the id.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*DC5ehJogpwh8h5FoXhLaUw.jpeg" /><figcaption>Photo by <a href="https://www.sciencedirect.com/science/article/abs/pii/S0028393213003990">www.sciencedirect.com</a></figcaption></figure><p>Nevertheless, Python tuples are immutable, except when they’re mutable. Tuples are more than just immutable lists, there is a bit of ambiguity here. We should also be aware of definitions of “mutable” and “value”, we can see that tuples’ values can sometimes change, i.e. mutate. It isn’t technically wrong to say that tuples can be mutable, though it will certainly raise eyebrows and require more explanation, same as Frozen Set.</p><p>Since it is not possible to change the object without changing its id, there will be no unexpected changes that can happen by changing the alias.</p><h3>Why do you treat mutable and immutable objects differently, why Python?</h3><p>Because of space, saving space indeed. Python takes advantage of this alias property of immutable objects. In other words, this language will automatically make an alias of immutable objects that have the same value.</p><p>To be sure, it is better to use “==” to check for the equality of two numbers, strings, or other types of variables, and “is” to compare their id.</p><p>Changing a mutable data type won’t change its memory address on the other hand changing an immutable type can produce errors.</p><p>Interesting information:</p><ul><li>Immutables are quicker to access than mutable objects.</li><li>Mutable objects are great to use when you need to change the size of the object, for example, a list, or dict. etc. Immutables are used when you need to ensure that the object you made will always stay the same.</li><li>Immutable objects are fundamentally expensive to “change” because doing so involves creating a copy. Changing mutable objects is cheap.</li><li>Python3 keeps an array of integer objects, NSMALLPOSINTS in the range -5 to 0 and NSMALLNEGINTS in the range of 0 to 256. Those values are the most used integers and they are pre-allocated. It is an array of 262 integers and this structure is used to access these integers fast. They get allocated right when you initialize your NSMALLPOSINTS and NSMALLNEGINTS macros.</li><li>Python passes (provide an argument to a function) neither by reference (this<strong> </strong>means that the argument you’re passing to the function is a <strong>reference</strong> to a variable that already exists in memory rather than an independent copy of that variable) nor by value, but <strong>by assignment (<em>creates object references instead of copying the objects)</em></strong></li><li>Instead of storing values in the memory space reserved by the variable, Python has the variable refer to the value. Similar to pointers in C, variables in Python refer to values (or objects) stored somewhere in memory. Python keeps an internal counter on how many references an object has. Once the counter goes to zero (meaning that no reference is made to the object) the garbage collector removes the object, thus freeing up the memory. If you want to know more <a href="http://foobarnbaz.com/2012/07/08/understanding-python-variables/">click here</a>.</li></ul><h3>When we passed arguments to functions, what are the implications for mutable and immutable objects?</h3><p>Arguments can be passed to functions either by value or by reference. If an object is mutable, then the reference to the object is sent into the function. However, if the method tries to change an immutable object, errors could happen. Therefore, Python will pass arguments that are referencing an immutable type as a value.</p><p>For example, integers are immutable, and their value is passed into the function through a parameter. The variable could be incremented but the value outside the function is unchanged.</p><p>A similar thing happens with strings, the originally referenced string is not changed by the function. Instead, a new string is created.</p><p>It’s important to know the difference between mutable and immutable types and how they are treated when passed into functions. Memory efficiency is highly affected when the proper objects are used.</p><p>If a mutable object is called by reference in a function, it can change the original variable. To avoid this, the original variable needs to be copied to another variable. Immutable objects can be called by reference because their value cannot be changed.</p><p>Something for you to remember:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*uWI7TKGcm4-bGVKIVYutFg.png" /><figcaption>Photo by <a href="http://swcarpentry.github.io/training-course/2013/03/concept-map-mutable-and-immutable-objects-in-python/">http://swcarpentry.github.io/</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe5ba3b83932" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>