{"id":28126,"date":"2018-06-25T13:31:51","date_gmt":"2018-06-25T13:31:51","guid":{"rendered":"http:\/\/www.sickgaming.net\/blog\/2018\/06\/25\/python-3-sometimes-immutable-is-mutable-and-everything-is-an-object\/"},"modified":"2018-06-25T13:31:51","modified_gmt":"2018-06-25T13:31:51","slug":"python-3-sometimes-immutable-is-mutable-and-everything-is-an-object","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2018\/06\/25\/python-3-sometimes-immutable-is-mutable-and-everything-is-an-object\/","title":{"rendered":"Python 3: Sometimes Immutable Is Mutable and Everything Is an Object"},"content":{"rendered":"<div><img decoding=\"async\" src=\"http:\/\/www.sickgaming.net\/blog\/wp-content\/uploads\/2018\/06\/python-3-sometimes-immutable-is-mutable-and-everything-is-an-object.png\" class=\"ff-og-image-inserted\" \/><\/div>\n<h3>What is Python?<\/h3>\n<p class=\"graf graf--p graf-after--figure\">Python is an\u00a0interpreted, interactive object-oriented programming language;\u00a0it\u00a0incorporated modules, classes, exceptions, dynamic typing and high level data types. Python is also powerful when it comes to clear syntax. It is a high-level general-purpose programming language that can be applied to many different classes of problems\u200a\u2014\u200awith a large standard library that encapsulates string processing (regular expressions, Unicode, calculating differences between files), Internet protocols (HTTP, FTP, SMTP, XML-RPC, POP, IMAP, CGI programming), software engineering (unit testing, logging, profiling, parsing Python code), and operating system interfaces (system calls, filesystems, TCP\/IP sockets). Here are some of Python\u2019s features:<\/p>\n<ul class=\"postList\">\n<li class=\"graf graf--li graf-after--p\">An\u00a0<em class=\"markup--em markup--li-em\">interpreted<\/em>\u00a0(as opposed to\u00a0<em class=\"markup--em markup--li-em\">compiled<\/em>) language. Contrary to C, for example, Python code does not need to be compiled before executing it. In addition, Python can be used\u00a0interactively: many Python interpreters are available, from which commands and scripts can be executed.<\/li>\n<li class=\"graf graf--li graf-after--li\">A free software released under an\u00a0open-source\u00a0license: Python can be used and distributed free of charge, even for building commercial software.<\/li>\n<li class=\"graf graf--li graf-after--li\">Multi-platform: Python is available for all major operating systems, Windows, Linux\/Unix, MacOS X, most likely your mobile phone OS, etc.<\/li>\n<li class=\"graf graf--li graf-after--li\">A very readable language with clear non-verbose syntax<\/li>\n<li class=\"graf graf--li graf-after--li\">A language for which a large variety of high-quality packages are available for various applications, from web frameworks to scientific computing.<\/li>\n<li class=\"graf graf--li graf-after--li\">A language very easy to interface with other languages, in particular C and C++.<\/li>\n<li class=\"graf graf--li graf-after--li\">Some other features of the language are illustrated just below. For example, Python is an object-oriented language, with dynamic typing (an object\u2019s type can change during the course of a program).<\/li>\n<\/ul>\n<h3 class=\"graf graf--h3 graf-after--li\">What does it mean to be\u00a0an object-oriented language?<\/h3>\n<p class=\"graf graf--p graf-after--h3\">Python is a multi-paradigm programming language. Meaning, it supports different programming approach. One of the popular approach to solve a programming problem is by creating objects. This is known as Object-Oriented Programming (OOP).<\/p>\n<p class=\"graf graf--p graf-after--p\">An object has two characteristics:<br \/>1) attributes<br \/>2) behavior<\/p>\n<p class=\"graf graf--p graf-after--p\">Let\u2019s take an example:<\/p>\n<p class=\"graf graf--p graf-after--p\">Dog is an object:<br \/>a) name, age, color are data<br \/>b) singing, dancing are behavior<\/p>\n<p class=\"graf graf--p graf-after--p\">We call\u00a0<em class=\"markup--em markup--p-em\">data<\/em>\u00a0as\u00a0<em class=\"markup--em markup--p-em\">attributes<\/em>\u00a0and\u00a0<em class=\"markup--em markup--p-em\">behavior<\/em>\u00a0as\u00a0<em class=\"markup--em markup--p-em\">methods<\/em>\u00a0in object oriented programming. Again:<\/p>\n<p class=\"graf graf--p graf-after--p\">Data \u2192 Attributes &amp; Behavior \u2192 Methods<\/p>\n<p class=\"graf graf--p graf-after--p\">The concept of OOP in Python focuses on creating reusable code. This concept is also known as DRY (Don\u2019t Repeat Yourself). In Python, the concept of OOP follows some basic principles:<\/p>\n<p class=\"graf graf--p graf-after--p\">Inheritance\u200a\u2014\u200aA process of using details from a new class without modifying existing class.<br \/>Encapsulation\u200a\u2014\u200aHiding the private details of a class from other objects.<br \/>Polymorphism\u200a\u2014\u200aA concept of using common operation in different ways for different data input.<\/p>\n<h3 class=\"graf graf--h3 graf-after--p\">Class<\/h3>\n<p class=\"graf graf--p graf-after--h3\">A class is a blueprint for the object.<\/p>\n<p class=\"graf graf--p graf-after--p\">We can think of class as an sketch of a dog with labels. It contains all the details about the name, colors, size etc. Based on these descriptions, we can study about the dog. Here, dog is an object.<\/p>\n<p class=\"graf graf--p graf-after--p\">The example for class of dog can be\u00a0:<\/p>\n<pre class=\"graf graf--pre graf-after--p\">\nclass Dog: pass<\/pre>\n<p class=\"graf graf--p graf-after--pre\">Here, we use\u00a0<code class=\"markup--code markup--p-code\">class<\/code>\u00a0keyword to define an empty class Dog. From class, we construct instances. An instance is a specific object created from a particular class.<\/p>\n<p class=\"graf graf--p graf-after--p\">A\u00a0Class\u00a0is the blueprint from which individual objects are created. In the real world we often find many objects with all the same type. Like cars. All the same make and model (have an engine, wheels, doors,\u00a0\u2026). Each car was built from the same set of blueprints and has the same components.<\/p>\n<h3 class=\"graf graf--h3 graf-after--p\">Object<\/h3>\n<p class=\"graf graf--p graf-after--h3\">Think of an object in Python as a block of memory, and a variable is just something that points\/references to that block of memory. All the information relevant to your data is stored within the object itself. And the variable stores the address to that object. So it actually doesn\u2019t matter if you reassign a variable pointing to an integer to point to a different data type.<\/p>\n<pre class=\"graf graf--pre graf-after--p\">\n&gt;&gt;&gt; a = 1\n&gt;&gt;&gt; a = \"I am a string now\"\n&gt;&gt;&gt; print(a)\nI am a string now<\/pre>\n<p class=\"graf graf--p graf-after--pre\">Every object has its own\u00a0identity\/ID\u00a0that stores its address in memory. Every object has a\u00a0type. An object can also hold references to other objects. For example, an integer will not have references to other objects but if the object is a list, it will contain references to each object within this list. We will touch up on this when we look at tuples later.<\/p>\n<p class=\"graf graf--p graf-after--p\">The built-in function\u00a0<code class=\"markup--code markup--p-code\">id()<\/code>\u00a0will return an object\u2019s id and\u00a0<code class=\"markup--code markup--p-code\">type()<\/code>\u00a0will return an object\u2019s type:<\/p>\n<pre class=\"graf graf--pre graf-after--p\">\n&gt;&gt;&gt; list_1 = [1, 2, 3]<\/pre>\n<pre class=\"graf graf--pre graf-after--pre\">\n# to access this object's value\n&gt;&gt;&gt; list_1 [1, 2, 3]<\/pre>\n<pre class=\"graf graf--pre graf-after--pre\">\n# to access this object's ID\n&gt;&gt;&gt; id(list_1) 140705683311624<\/pre>\n<pre class=\"graf graf--pre graf-after--pre\">\n# to access object's data type\n&gt;&gt;&gt; type(list_1) &lt;class 'list'&gt;<\/pre>\n<p class=\"graf graf--p graf-after--pre\">So, an object (instance) is an instantiation of a class. When class is defined, only the description for the object is defined. Therefore, no memory or storage is allocated.<\/p>\n<p class=\"graf graf--p graf-after--p\">The example for object of class Dog can be:<\/p>\n<pre class=\"graf graf--pre graf-after--p\">\nobj = Dog()<\/pre>\n<p class=\"graf graf--p graf-after--pre\">Here, obj is object of class\u00a0<code class=\"markup--code markup--p-code\">Dog<\/code>.<\/p>\n<p class=\"graf graf--p graf-after--p\">Suppose we have details of Dog. Now, we are going to show how to build the class and objects of Dog.<\/p>\n<pre class=\"graf graf--pre graf-after--p\">\nclass Dog:<\/pre>\n<pre class=\"graf graf--pre graf-after--pre\">\n#class attribute species = \"animal\"<\/pre>\n<pre class=\"graf graf--pre graf-after--pre\">\n# instance attribute def __init__(self, name, age): self.name = name self.age = age<\/pre>\n<pre class=\"graf graf--pre graf-after--pre\">\n# instantiate the Dog class\nblu = Dog(\"Blu\", 10)\nwoo = Dog(\"Woo\", 15)<\/pre>\n<pre class=\"graf graf--pre graf-after--pre\">\n# access the class attributes\nprint(\"Blu is an {}\".format(blu.__class__.species))\nprint(\"Woo is also an {}\".format(woo.__class__.species))<\/pre>\n<pre class=\"graf graf--pre graf-after--pre\">\n# access the instance attributes\nprint(\"{} is {} years old\".format( blu.name, blu.age))\nprint(\"{} is {} years old\".format( woo.name, woo.age))<\/pre>\n<p class=\"graf graf--p graf-after--pre\">When we run the program, the output will be:<\/p>\n<pre class=\"graf graf--pre graf-after--p\">\nBlu is an animal\nWoo is also an animal\nBlu is 10 years old\nWoo is 15 years old<\/pre>\n<p class=\"graf graf--p graf-after--pre\">In the above program, we create a class with name Dog. Then, we define attributes. The attributes are a characteristic of an object.<\/p>\n<p class=\"graf graf--p graf-after--p\">Then, we create instances of the Dog class. Here, blu and woo are references (value) to our new objects.<\/p>\n<p class=\"graf graf--p graf-after--p\">Then, we access the class attribute using\u00a0<code class=\"markup--code markup--p-code\">__class __.species<\/code>. Class attributes are same for all instances of a class. Similarly, we access the instance attributes using\u00a0<code class=\"markup--code markup--p-code\">blu.name<\/code>\u00a0and\u00a0<code class=\"markup--code markup--p-code\">blu.age<\/code>. However, instance attributes are different for every instance of a class.<\/p>\n<p class=\"graf graf--p graf-after--p\">Let\u2019s try to understand how value and identity are affected if you use operators \u201c==\u201d and \u201cis\u201d<\/p>\n<p class=\"graf graf--p graf-after--p\">The \u201c==\u201d operator compares values whereas \u201cis\u201d operator compares identities. Hence, a is b is similar to id(a) == id(y), but two different objects may share the same value, but they will never share the same identity.<\/p>\n<p class=\"graf graf--p graf-after--p\">Example:<\/p>\n<pre class=\"graf graf--pre graf-after--p\">\n&gt;&gt;&gt; a = ['blu', 'woof']\n&gt;&gt;&gt; id(a)\n1877152401480\n&gt;&gt;&gt; b = a\n&gt;&gt;&gt; id(b)\n1877152401480\n&gt;&gt;&gt; id(a) == id(b)\nTrue\n&gt;&gt;&gt; a is b\nTrue\n&gt;&gt;&gt; c = ['blu', 'woof']\n&gt;&gt;&gt; a == c\nTrue\n&gt;&gt;&gt; id(c)\n1877152432200\n&gt;&gt;&gt; id(a) == id(c)\nFalse<\/pre>\n<h3 class=\"graf graf--h3 graf-after--pre\">Hashability<\/h3>\n<h4 class=\"graf graf--h4 graf-after--h3\">What is a\u00a0hash?<\/h4>\n<blockquote class=\"graf graf--blockquote graf-after--h4\">\n<p><a class=\"markup--anchor markup--blockquote-anchor\" href=\"https:\/\/docs.python.org\/3\/glossary.html#term-hashable\">According to Python\u00a0, \u201cAn object is hashable if it has a hash value which never changes during its lifetime\u201d, if and only if the object is immutable.<\/a><\/p>\n<\/blockquote>\n<p class=\"graf graf--p graf-after--blockquote\">A hash is an integer that depends on an object\u2019s value, and objects with the same value\u00a0always\u00a0have the same hash. (Objects with different values will occasionally have the same hash too. This is called a\u00a0<a class=\"markup--anchor markup--p-anchor\" href=\"https:\/\/stackoverflow.com\/a\/17586126\/1893164\"><em class=\"markup--em markup--p-em\">hash collision<\/em><\/a>.) While\u00a0<code class=\"markup--code markup--p-code\">id()<\/code>\u00a0will return an integer based on an object&#8217;s identity, the\u00a0<code class=\"markup--code markup--p-code\">hash()<\/code>\u00a0function will return an integer (the object&#8217;s hash) based on the hashable object&#8217;s value:<\/p>\n<pre class=\"graf graf--pre graf-after--p\">\n&gt;&gt;&gt; a = ('cow', 'bull')\n&gt;&gt;&gt; b = ('cow', 'bull')\n&gt;&gt;&gt; a == b\nTrue\n&gt;&gt;&gt; a is b\nFalse\n&gt;&gt;&gt; hash(a)\n6950940451664727300\n&gt;&gt;&gt; hash(b)\n6950940451664727300\n&gt;&gt;&gt; hash(a) == hash(b)\nTrue<\/pre>\n<p class=\"graf graf--p graf-after--pre\">Immutable objects can be hashable, mutable objects can\u2019t be hashable.This is important to know, because (for reasons beyond the scope of this post)\u00a0<a class=\"markup--anchor markup--p-anchor\" href=\"https:\/\/stackoverflow.com\/questions\/17585730\/what-does-hash-do-in-python\">only hashable objects can be used as keys in a dictionary or as items in a set<\/a>. Since hashes are based on values and only immutable objects can be hashable, this means that hashes will never change during the object\u2019s lifetime.<\/p>\n<p class=\"graf graf--p graf-after--p\">Hashability will be covered more under the mutable vs immutable object section, as sometimes a tuple can be mutable and how does that change values and understanding of mutable objects and immutable objects.<\/p>\n<p class=\"graf graf--p graf-after--p\">To summarize, EVERYTHING is an object in Python the only difference is some are mutable and some immutable. Wait but what kind of objects are possible in Python and which ones are mutable and which ones aren\u2019t?<\/p>\n<p class=\"graf graf--p graf-after--p\"><em class=\"markup--em markup--p-em\">Objects of built-in types like (bytes, int, float, bool, str, tuple, unicode, complex) are immutable. Objects of built-in types like (list, set, dict, array, bytearray) are mutable. Custom classes are mutable. To simulate immutability in a class, one should override attribute setting and deletion to raise exceptions.<\/em><\/p>\n<p class=\"graf graf--p graf-after--figure\">Now how would a newbie know which variables are mutable objects and which ones are not? For this we use 2 very handy built-in functions called id() and type()<\/p>\n<h3 class=\"graf graf--h3 graf-after--p\">What is id() and\u00a0type()?<\/h3>\n<pre class=\"graf graf--pre graf-after--h3\">\nSyntax to use id()\nid(object)<\/pre>\n<p class=\"graf graf--p graf-after--pre\">As we can see the function accepts a single parameter and is used to return the identity of an object.\u00a0This identity has to be unique and constant for this object during the lifetime.\u00a0Two objects with non-overlapping lifetimes may have the same id() value. If we relate this to C, then they are actually the memory address, here in Python it is the unique id. This function is generally used internally in Python.<\/p>\n<p class=\"graf graf--p graf-after--p\">Examples:<\/p>\n<pre class=\"graf graf--pre graf-after--p\">\nThe output is the identity of the object passed. This is random but when running in the same program, it generates unique and same identity. <\/pre>\n<pre class=\"graf graf--pre graf-after--pre\">\nInput : id(2507)\nOutput : 140365829447504\nOutput varies with different runs<\/pre>\n<pre class=\"graf graf--pre graf-after--pre\">\nInput : id(\"Holberton\")\nOutput : 139793848214784<\/pre>\n<h3 class=\"graf graf--h3 graf-after--pre\">What is an\u00a0Alias?<\/h3>\n<pre class=\"graf graf--pre graf-after--h3\">\n&gt;&gt;&gt; a = 1\n&gt;&gt;&gt; id(a)\n1904391232\n&gt;&gt;&gt; b = a #aliasing a\n&gt;&gt;&gt; id(b)\n1904391232\n&gt;&gt;&gt; b\n1<\/pre>\n<p class=\"graf graf--p graf-after--pre\"><em class=\"markup--em markup--p-em\">An alias is a second name for a piece of data. Programmers use\/ create aliases because it\u2019s often easier and faster to refer data than to copy it. If the data that is being created and assigned is immutable then aliasing does not matter as the data won\u2019t change, but there will be a lot of bugs if the data is mutable as it will lead to some issues like see below \u2014<\/em><\/p>\n<pre class=\"graf graf--pre graf-after--p\">\n&gt;&gt;&gt; a = 1\n&gt;&gt;&gt; id(a)\n1904391232\n&gt;&gt;&gt; b = a #aliasing a\n&gt;&gt;&gt; id(b)\n1904391232\n&gt;&gt;&gt; b\n1\n&gt;&gt;&gt; a = 2\n&gt;&gt;&gt; id(2)\n1904391264\n&gt;&gt;&gt; id(b)\n1904391232\n&gt;&gt;&gt; b\n1\n&gt;&gt;&gt; a\n2<\/pre>\n<p class=\"graf graf--p graf-after--pre\">as it can be seen a now points to 2 and id is different as compared to b which is still pointing to 1. In Python, aliasing happens whenever one variable\u2019s value is assigned to another variable, because variables are just names that store references to values.<\/p>\n<p class=\"graf graf--p graf-after--p\"><code class=\"markup--code markup--p-code\">type()<\/code>\u00a0method returns class type of the argument(object) passed as parameter. type() function is mostly used for debugging purposes.<\/p>\n<p class=\"graf graf--p graf-after--p\">Two different types of arguments can be passed to type() function, single and three argument. If single argument\u00a0<code class=\"markup--code markup--p-code\">type(obj)<\/code>\u00a0is passed, it returns the type of given object.<\/p>\n<p class=\"graf graf--p graf-after--p\">Syntax\u00a0:<\/p>\n<pre class=\"graf graf--pre graf-after--p\">\n<code class=\"markup--code markup--pre-code\">type(object)<\/code><\/pre>\n<p class=\"graf graf--p graf-after--pre\">We can find out what class an object belongs to using the built-in\u00a0<code class=\"markup--code markup--p-code\">type()<\/code>function:<\/p>\n<pre class=\"graf graf--pre graf-after--p\">\n&gt;&gt;&gt; Blue = [1, 2, 3]\n&gt;&gt;&gt; type(Blue)\n&lt;class 'list'&gt;<\/pre>\n<pre class=\"graf graf--pre graf-after--pre\">\n&gt;&gt;&gt; def my_func(x)\n... x = 89\n&gt;&gt;&gt; type(my_func)\n&lt;class 'function'&gt;<\/pre>\n<p class=\"graf graf--p graf-after--pre\">Now that we can compare variables to see their type and id\u2019s, we can dive in deeper to understand how mutable and immutable objects work.<\/p>\n<h3 class=\"graf graf--h3 graf-after--p\">Mutable Objects vs. Immutable Objects<\/h3>\n<p class=\"graf graf--p graf-after--h3\">Not all Python objects handle changes the same way. Some objects are mutable, meaning they can be altered. Others are immutable; they cannot be changed but rather return new objects when attempting to update. What does this mean when writing Python code?<\/p>\n<p class=\"graf graf--p graf-after--p\">The following are some\u00a0mutable\u00a0objects:<\/p>\n<ul class=\"postList\">\n<li class=\"graf graf--li graf-after--p\">list<\/li>\n<li class=\"graf graf--li graf-after--li\">dict<\/li>\n<li class=\"graf graf--li graf-after--li\">set<\/li>\n<li class=\"graf graf--li graf-after--li\">bytearray<\/li>\n<li class=\"graf graf--li graf-after--li\">user-defined classes (unless specifically made immutable)<\/li>\n<\/ul>\n<p class=\"graf graf--p graf-after--li\">The following are some\u00a0immutable\u00a0objects:<\/p>\n<ul class=\"postList\">\n<li class=\"graf graf--li graf-after--p\">int<\/li>\n<li class=\"graf graf--li graf-after--li\">float<\/li>\n<li class=\"graf graf--li graf-after--li\">decimal<\/li>\n<li class=\"graf graf--li graf-after--li\">complex<\/li>\n<li class=\"graf graf--li graf-after--li\">bool<\/li>\n<li class=\"graf graf--li graf-after--li\">string<\/li>\n<li class=\"graf graf--li graf-after--li\">tuple<\/li>\n<li class=\"graf graf--li graf-after--li\">range<\/li>\n<li class=\"graf graf--li graf-after--li\">frozenset<\/li>\n<li class=\"graf graf--li graf-after--li\">bytes<\/li>\n<\/ul>\n<p class=\"graf graf--p graf-after--li\">The distinction is rather simple: mutable objects can change, whereas immutable objects cannot. Immutable literally means not mutable.<\/p>\n<p class=\"graf graf--p graf-after--p\">A standard example are\u00a0<code class=\"markup--code markup--p-code\">tuple<\/code>\u00a0and\u00a0<code class=\"markup--code markup--p-code\">list<\/code>: A\u00a0<code class=\"markup--code markup--p-code\">tuple<\/code>\u00a0is filled on creation, and then is frozen &#8211; its content cannot change anymore. To a\u00a0<code class=\"markup--code markup--p-code\">list<\/code>, one can append elements, set elements and delete elements at any time. Although keep in mind exceptions:\u00a0<em class=\"markup--em markup--p-em\">tuple<\/em>\u00a0is an\u00a0immutable\u00a0list whereas\u00a0<em class=\"markup--em markup--p-em\">frozenset<\/em>\u00a0is an\u00a0immutable\u00a0<em class=\"markup--em markup--p-em\">set<\/em>. Quoting\u00a0<a class=\"markup--anchor markup--p-anchor\" href=\"https:\/\/stackoverflow.com\/a\/14422446\">stackoverflow\u00a0<\/a>answer-<code class=\"markup--code markup--p-code\">Tuples<\/code>\u00a0are indeed an ordered collection of objects, but they can contain duplicates and unhashable objects, and have slice functionality\u00a0<code class=\"markup--code markup--p-code\">frozensets<\/code>\u00a0aren&#8217;t indexed, but you have the functionality of\u00a0<code class=\"markup--code markup--p-code\">sets<\/code>\u00a0&#8211; O(1) element lookups, and functionality such as unions and intersections. They also can&#8217;t contain duplicates, like their mutable counterparts.<\/p>\n<p class=\"graf graf--p graf-after--p\">Let\u2019s create a dictionary with immutable objects for keys \u2014<\/p>\n<pre class=\"graf graf--pre graf-after--p\">\n&gt;&gt;&gt; a = {\u2018blu\u2019: 42, True: \u2018woof\u2019, (\u2018x\u2019, \u2018y\u2019, \u2018z\u2019): [\u2018hello\u2019]}\n&gt;&gt;&gt; a.keys()\ndict_keys([\u2018blu\u2019, True, (\u2018x\u2019, \u2018y\u2019, \u2018z\u2019)])<\/pre>\n<p class=\"graf graf--p graf-after--pre\">As seen above keys in a are immutable, hashable objects, but if you try to call hash() on a mutable object(such as sets), or trying to use a mutable object for a dictionary key, an error will be raised:<\/p>\n<pre class=\"graf graf--pre graf-after--p\">\n&gt;&gt;&gt; spam = {['hello', 'world']: 42}\nTraceback (most recent call last): File \"&lt;stdin&gt;\", line 1, in &lt;module&gt;\nTypeError: unhashable type: 'list' &gt;&gt;&gt; d = {'a': 1}\n&gt;&gt;&gt; spam = {d: 42}\nTraceback (most recent call last): File \"&lt;stdin&gt;\", line 1, in &lt;module&gt;\nTypeError: unhashable type: 'dict'<\/pre>\n<p class=\"graf graf--p graf-after--pre\">So, tuples, being immutable objects, can be used as dictionary keys?<\/p>\n<pre class=\"graf graf--pre graf-after--p\">\n&gt;&gt;&gt; spam = {('a', 'b', 'c'): 'hello'}\nTraceback (most recent call last): File \"&lt;stdin&gt;\", line 1, in &lt;module&gt;\nTypeError: unhashable type: 'list'<\/pre>\n<p class=\"graf graf--p graf-after--pre\">As\u00a0seen above, if a tuple contains a mutable object, according to the previous explanation about hashability it cannot be hashed. So, immutable objects\u00a0<em class=\"markup--em markup--p-em\">can<\/em>\u00a0be hashable, but this doesn\u2019t necessarily mean they\u2019re\u00a0<em class=\"markup--em markup--p-em\">always<\/em>hashable. And remember, the hash is derived from the object\u2019s value.<\/p>\n<p class=\"graf graf--p graf-after--p\">This is an interesting corner case: a tuple (which should be immutable) that contains a mutable list cannot be hashed. This is because the hash of the tuple depends on the tuple\u2019s value, but if that list\u2019s value can change, that means the tuple\u2019s value can change and therefore the hash can change during the tuple\u2019s lifetime.<\/p>\n<p class=\"graf graf--p graf-after--p\">So far it is now understood that some tuples are hashable\u200a\u2014\u200aimmutable but some other tuple are not hashable\u200a\u2014\u200amutable. According to official Python documentation immutable and mutable are defined as\u200a\u2014\u200a<a class=\"markup--anchor markup--p-anchor\" href=\"https:\/\/docs.python.org\/3\/glossary.html#term-immutable\">\u201cAn object with a fixed value\u201d<\/a>\u00a0and\u00a0<a class=\"markup--anchor markup--p-anchor\" href=\"https:\/\/docs.python.org\/3\/glossary.html#term-mutable\">\u201cMutable objects can change their value\u201d<\/a>. This can possibly mean that mutability is a property of objects, hence it makes sense that some tuples will be mutable while others won\u2019t be.<\/p>\n<pre class=\"graf graf--pre graf-after--p\">\n&gt;&gt;&gt; a = ('dogs', 'cats', [1, 2, 3])\n&gt;&gt;&gt; b = ('dogs', 'cats', [1, 2, 3])\n&gt;&gt;&gt; a == b\nTrue\n&gt;&gt;&gt; a is b\nFalse\n&gt;&gt;&gt; a[2].append(99)\n&gt;&gt;&gt; a\n('dogs', 'cats', [1, 2, 3, 99])\n&gt;&gt;&gt; a == b\nFalse<\/pre>\n<p class=\"graf graf--p graf-after--pre\">In this example, the tuples a and b have equal (==) values but are different objects, so when list is changed in tuple a the values get changed as a is not longer == b and did not change values of b. This example states that tuples are mutable.<\/p>\n<p class=\"graf graf--p graf-after--p\">While Python tends towards mutability, there are many use-cases for immutability as well. Here are some straightforward ones:<\/p>\n<ul class=\"postList\">\n<li class=\"graf graf--li graf-after--p\">Mutable objects are great for efficiently passing around data. Let\u2019s say object\u00a0<code class=\"markup--code markup--li-code\">anton<\/code>\u00a0and\u00a0<code class=\"markup--code markup--li-code\">berta<\/code>\u00a0have access to the same\u00a0<code class=\"markup--code markup--li-code\">list<\/code>.\u00a0<code class=\"markup--code markup--li-code\">anton<\/code>\u00a0adds\u00a0<code class=\"markup--code markup--li-code\">\u201clemons\u201d<\/code>\u00a0to the list, and\u00a0<code class=\"markup--code markup--li-code\">berta<\/code>\u00a0automatically has access to this information.<br \/>If both would use a\u00a0<code class=\"markup--code markup--li-code\">tuple<\/code>, anton would have to\u00a0<em class=\"markup--em markup--li-em\">copy<\/em>\u00a0the entries of his shopping-tuple,\u00a0<em class=\"markup--em markup--li-em\">add<\/em>\u00a0the new element,\u00a0<em class=\"markup--em markup--li-em\">create<\/em>\u00a0a new tuple, then\u00a0<em class=\"markup--em markup--li-em\">send<\/em>\u00a0that to\u00a0<code class=\"markup--code markup--li-code\">berta<\/code>. Even if both can talk directly, that is a lot of work.<\/li>\n<li class=\"graf graf--li graf-after--li\">Immutable objects are great for working with the data. So\u00a0<code class=\"markup--code markup--li-code\">berta<\/code>\u00a0is going to buy all that stuff &#8211; she can read everything, make a plan, and does not have to double check for changes. If next week, she needs to buy more stuff for the same shopping-tuple,\u00a0<code class=\"markup--code markup--li-code\">berta<\/code>\u00a0just reuses the old plan. She has the guarantee that\u00a0<code class=\"markup--code markup--li-code\">anton<\/code>\u00a0<em class=\"markup--em markup--li-em\">cannot<\/em>\u00a0change anything unnoticed.<br \/>If both would use a\u00a0<code class=\"markup--code markup--li-code\">list<\/code>,\u00a0<code class=\"markup--code markup--li-code\">berta<\/code>\u00a0could not plan ahead. She has no guarantee that\u00a0<code class=\"markup--code markup--li-code\">\u201clemons\u201d<\/code>\u00a0are still on the list when she arrives at the shop. She has no guarantee that next week, she can just repeat what was appropriate last week.<\/li>\n<\/ul>\n<p class=\"graf graf--p graf-after--li\">You should generally use mutable objects when having to deal with growing data. For example, when parsing a file, you may append information from each line to a list. Custom objects are usually mutable, buffering data, adjusting to new conditions and so on. In general, whenever something can change, mutable objects are much easier.<\/p>\n<p class=\"graf graf--p graf-after--p\">Immutable objects are sparingly used in python\u200a\u2014\u200ausually, it is implicit such as using\u00a0<code class=\"markup--code markup--p-code\">int<\/code>\u00a0or other basic, immutable types. Often, you will be using mutable types as de-facto immutable &#8211; many\u00a0<code class=\"markup--code markup--p-code\">list<\/code>s are filled at construction and never changed. There is also no immutable\u00a0<code class=\"markup--code markup--p-code\">dict<\/code>. You should enforce immutability to optimise algorithms, e.g. to do caching.<\/p>\n<p class=\"graf graf--p graf-after--p\">Interestingly enough, python\u2019s often-used\u00a0<code class=\"markup--code markup--p-code\">dict<\/code>\u00a0requires keys to be immutable. It is a data structure that\u00a0<em class=\"markup--em markup--p-em\">cannot<\/em>\u00a0work with mutable objects, since it relies on some features being guaranteed for its elements.<\/p>\n<h4 class=\"graf graf--h4 graf-after--p\">Mutable example<\/h4>\n<pre class=\"graf graf--pre graf-after--h4\">\n&gt;&gt;&gt; my_list = [10, 20, 30]\n&gt;&gt;&gt; print(my_list)<\/pre>\n<pre class=\"graf graf--pre graf-after--pre\">\n[10, 20, 30]<\/pre>\n<pre class=\"graf graf--pre graf-after--pre\">\n&gt;&gt;&gt; my_list = [10, 20, 30]\n&gt;&gt;&gt; my_list[0] = 40\n&gt;&gt;&gt; print(my_list)<\/pre>\n<pre class=\"graf graf--pre graf-after--pre\">\n[40, 20, 30]<\/pre>\n<h4 class=\"graf graf--h4 graf-after--pre\">Immutable example<\/h4>\n<pre class=\"graf graf--pre graf-after--h4\">\n&gt;&gt;&gt; tuple_ = (10, 20, 30)\n&gt;&gt;&gt; print(tuple_)<\/pre>\n<pre class=\"graf graf--pre graf-after--pre\">\n[10, 20, 30]<\/pre>\n<pre class=\"graf graf--pre graf-after--pre\">\n&gt;&gt;&gt; tuple_ = [10, 20, 30]\n&gt;&gt;&gt; tuple_[0] = 40\n&gt;&gt;&gt; print(tuple_)<\/pre>\n<pre class=\"graf graf--pre graf-after--pre\">\nTraceback (most recent call last): File \"test.py\", line 3, in &lt; module &gt; my_yuple[0] = 40\nTypeError: 'tuple' object does not support item assignment<\/pre>\n<p class=\"graf graf--p graf-after--pre\">If you want to write most efficient code, you should be the knowing difference between\u00a0mutable\u00a0and\u00a0immutable\u00a0in python. Concatenating string in loops wastes lots of\u00a0memory\u00a0, because strings are immutable, concatenating two strings together actually creates a third string which is the combination of the previous two. If you are iterating a lot and building a large string, you will waste a lot of memory creating and throwing away objects. Use list compression join technique.<\/p>\n<p class=\"graf graf--p graf-after--p\">Python handles mutable and immutable objects differently.\u00a0Immutable\u00a0are quicker to access than mutable objects. Also, immutable objects are fundamentally expensive to \u201cchange\u201d, because doing so involves creating a copy. Changing\u00a0mutable\u00a0objects is cheap.<\/p>\n<h3 class=\"graf graf--h3 graf-after--p\">Interning, integer caching and everything called: NSMALLPOSINTS &amp; NSMALLNEGINTS<\/h3>\n<p class=\"graf graf--p graf-after--h3\">Easy things first \u2014<\/p>\n<p class=\"graf graf--p graf-after--p\"><code class=\"markup--code markup--p-code\">NSMALLNEGINTS<\/code>\u00a0is in the range -5 to 0 and\u00a0<code class=\"markup--code markup--p-code\">NSMALLPOSINTS<\/code>\u00a0is in the 0 to 256 range. These are macros defined in Python\u200a\u2014\u200aearlier versions ranged from\u00a0<a class=\"markup--anchor markup--p-anchor\" href=\"https:\/\/github.com\/python\/cpython\/commit\/842d2ccdcd540399501a918b9724d2eaf5599f39\">-1 to 99<\/a>, then\u00a0<a class=\"markup--anchor markup--p-anchor\" href=\"https:\/\/github.com\/python\/cpython\/commit\/c91ed400e053dc9f11dd30c84e2bb611999dce50\">-5 to 99<\/a>\u00a0and finally\u00a0<a class=\"markup--anchor markup--p-anchor\" href=\"https:\/\/github.com\/python\/cpython\/commit\/418a1ef0895e826c65d4113be5d86891c199e15d\">-5 to 256<\/a>. Python keeps an array of integer objects for \u201call integers between -5 and 256\u201d. When creating an int in that range, it is actually just getting a reference to the existing object in memory.<\/p>\n<p class=\"graf graf--p graf-after--p\">If x = 42, what happens actually is Python performing a search in the integer block for the value in the range -5 to 256. Once x falls out of the scope of this range, it will be garbage collected (destroyed) and be an entirely different object. The process of creating a new integer object and then destroying it immediately creates a lot of useless calculation cycles, so Python preallocated a range of commonly used integers.<\/p>\n<p class=\"graf graf--p graf-after--p\">There are exception to immutable objects as stated above by making a tuple \u201cmutable\u201d. As it is known a new object is created each time a variable makes a reference to it, it does happen slightly differently for a few things &#8211;<\/p>\n<p class=\"graf graf--p graf-after--p\">a) Strings without whitespaces and less than 20 characters<br \/>b) Integers between -5 to 256 (including both as explained above)<br \/>c) empty immutable objects (tuples)<\/p>\n<p class=\"graf graf--p graf-after--p\">These objects are always reused or\u00a0<em class=\"markup--em markup--p-em\">interned<\/em>. This is due memory optimization in Python implementation. The rationale behind doing this is as follows:<\/p>\n<ol class=\"postList\">\n<li class=\"graf graf--li graf-after--p\">Since programmers use these objects frequently, interning existing objects saves memory.<\/li>\n<li class=\"graf graf--li graf-after--li\">Since immutable objects like tuples and strings cannot be modified, there is no risk in interning the same object.<\/li>\n<\/ol>\n<p class=\"graf graf--p graf-after--li\">So what does it mean by\u00a0\u201cinterning\u201d?<\/p>\n<p class=\"graf graf--p graf-after--p\"><em class=\"markup--em markup--p-em\">interning\u00a0<\/em>allows two variables to refer to the\u00a0<em class=\"markup--em markup--p-em\">same string object<\/em>. Python automatically does this, although the exact rules remain fuzzy. One can also forcibly intern strings by calling the\u00a0<code class=\"markup--code markup--p-code\">intern()<\/code>function.\u00a0<a class=\"markup--anchor markup--p-anchor\" href=\"http:\/\/guilload.com\/python-string-interning\/\">Guillo\u2019s article<\/a>provides an in-depth look into string interning.<\/p>\n<p class=\"graf graf--p graf-after--p\">Example of string interning with more than 20 characters or whitespace will be new objects:<\/p>\n<pre class=\"graf graf--pre graf-after--p\">\n&gt;&gt;&gt; a = \"Howdy! How are you?\"\n&gt;&gt;&gt; b = \"Howdy! How are you?\"\n&gt;&gt;&gt; a is b\nFalse<\/pre>\n<p class=\"graf graf--p graf-after--pre\">but, if a string is less than 20 char and no whitespace it will look somewhat like this:<\/p>\n<pre class=\"graf graf--pre graf-after--p\">\n&gt;&gt;&gt; a = \"python\"\n&gt;&gt;&gt; b = \"python\"\n&gt;&gt;&gt; a is b\nTrue<\/pre>\n<p class=\"graf graf--p graf-after--pre\">As a and b refer to the same objects.<\/p>\n<p class=\"graf graf--p graf-after--p\">Let\u2019s move on to integers now.<\/p>\n<p class=\"graf graf--p graf-after--p\">As explained above in macro definition integer caching is happening because of preload python definition of commonly used integers. Hence, variables referring to an integer within the range would be pointing to the same object that already exists in memory:<\/p>\n<pre class=\"graf graf--pre graf-after--p\">\n&gt;&gt;&gt; a = 256\n&gt;&gt;&gt; b = 256\n&gt;&gt;&gt; a is b\nTrue<\/pre>\n<p class=\"graf graf--p graf-after--pre\">This is not the case if the object referred to is outside the range:<\/p>\n<pre class=\"graf graf--pre graf-after--p\">\n&gt;&gt;&gt; a = 1024\n&gt;&gt;&gt; b = 1024\n&gt;&gt;&gt; a is b\nFalse<\/pre>\n<p class=\"graf graf--p graf-after--pre\">Lastly, let\u2019s talk about empty immutable objects:<\/p>\n<pre class=\"graf graf--pre graf-after--p\">\n&gt;&gt;&gt; a = ()\n&gt;&gt;&gt; b = ()\n&gt;&gt;&gt; a is b\nTrue<\/pre>\n<p class=\"graf graf--p graf-after--pre\">Here a and b refer to the same object in memory as it is an empty tuple, but this changes if the tuple is not empty.<\/p>\n<pre class=\"graf graf--pre graf-after--p\">\n&gt;&gt;&gt; a = (1, 2)\n&gt;&gt;&gt; b = (1, 2)\n&gt;&gt;&gt; a == b\nTrue\n&gt;&gt;&gt; a is b\nFalse<\/pre>\n<h3 class=\"graf graf--h3 graf-after--pre\">Passing mutable and immutable objects into functions:<\/h3>\n<p class=\"graf graf--p graf-after--h3\">Immutable and mutable objects or variables are handled differently while working with function arguments. In the following diagram, variables\u00a0<code class=\"markup--code markup--p-code\">a<\/code>,\u00a0<code class=\"markup--code markup--p-code\">b<\/code>and\u00a0<code class=\"markup--code markup--p-code\">name<\/code>\u00a0point to their memory locations where the actual value of the object is stored.<\/p>\n<h3 class=\"graf graf--h3 graf-after--figure\">Major Concepts of Function Argument Passing in\u00a0Python<\/h3>\n<p class=\"graf graf--p graf-after--h3\">Arguments are always\u00a0passed to functions by object\u00a0in Python. The caller and the function code blocks share the same object or variable. When we change the value of a function argument inside the function code block scope, the value of that variable also changes inside the caller code block scope regardless of the name of the argument or variable. This concept behaves differently for both\u00a0mutable and immutable arguments in Python.<\/p>\n<p class=\"graf graf--p graf-after--p\">In Python,\u00a0<code class=\"markup--code markup--p-code\">integer<\/code>,\u00a0<code class=\"markup--code markup--p-code\">float<\/code>,\u00a0<code class=\"markup--code markup--p-code\">string<\/code>\u00a0and\u00a0<code class=\"markup--code markup--p-code\">tuple<\/code>\u00a0are immutable objects.\u00a0<code class=\"markup--code markup--p-code\">list<\/code>,\u00a0<code class=\"markup--code markup--p-code\">dict<\/code>\u00a0and\u00a0<code class=\"markup--code markup--p-code\">set<\/code>\u00a0fall in the mutable object category. This means the value of\u00a0<code class=\"markup--code markup--p-code\">integer<\/code>,\u00a0<code class=\"markup--code markup--p-code\">float<\/code>,\u00a0<code class=\"markup--code markup--p-code\">string<\/code>\u00a0or\u00a0<code class=\"markup--code markup--p-code\">tuple<\/code>\u00a0is not changed in the calling block if their value is changed inside the function or method block but the value of\u00a0<code class=\"markup--code markup--p-code\">list<\/code>,\u00a0<code class=\"markup--code markup--p-code\">dict<\/code>\u00a0or\u00a0<code class=\"markup--code markup--p-code\">set<\/code>\u00a0object is changed.<\/p>\n<h3 class=\"graf graf--h3 graf-after--p\">Python Immutable Function Arguments<\/h3>\n<p class=\"graf graf--p graf-after--h3\">Python immutable objects, such as\u00a0<code class=\"markup--code markup--p-code\">numbers<\/code>,\u00a0<code class=\"markup--code markup--p-code\">tuple<\/code>\u00a0and\u00a0<code class=\"markup--code markup--p-code\">strings<\/code>, are also passed by reference like mutable objects, such as\u00a0<code class=\"markup--code markup--p-code\">list<\/code>,<code class=\"markup--code markup--p-code\">\u00a0set<\/code>\u00a0and\u00a0<code class=\"markup--code markup--p-code\">dict.<\/code>\u00a0Due to state of immutable (unchangeable) objects if an integer or string value is changed inside the function block then it much behaves like an object copying. A local new duplicate copy of the caller object inside the function block scope is created and manipulated. The caller object will remain unchanged. Therefore, caller block will not notice any changes made inside the function block scope to the immutable object. Let\u2019s take a look at the following example.<\/p>\n<h3 class=\"graf graf--h3 graf-after--p\">Python Immutable Function Argument\u200a\u2014\u200aExample and Explanation<\/h3>\n<pre class=\"graf graf--pre graf-after--h3\">\ndef foo1(a):\n<em class=\"markup--em markup--pre-em\"># function block\n<\/em>a += 1\nprint(\u2018id of a:\u2019, id(a)) <em class=\"markup--em markup--pre-em\"># id of y and a are same<\/em><\/pre>\n<pre class=\"graf graf--pre graf-after--pre\">\nreturn a<\/pre>\n<pre class=\"graf graf--pre graf-after--pre\">\n<em class=\"markup--em markup--pre-em\"># main or caller block\n<\/em>x = 10\ny = foo1(x)<\/pre>\n<pre class=\"graf graf--pre graf-after--pre\">\n<em class=\"markup--em markup--pre-em\"># value of x is unchanged\n<\/em>print(\u2018x:\u2019, x)<\/pre>\n<pre class=\"graf graf--pre graf-after--pre\">\n<em class=\"markup--em markup--pre-em\"># value of y is the return value of the function foo1<\/em><\/pre>\n<pre class=\"graf graf--pre graf-after--pre\">\n<em class=\"markup--em markup--pre-em\"># after adding 1 to argument \u2018a\u2019 which is actual variable \u2018x\u2019\n<\/em>print(\u2018y:\u2019, y)\nprint(\u2018id of x:\u2019, id(x)) <em class=\"markup--em markup--pre-em\"># id of x\n<\/em>print(\u2018id of y:\u2019, id(y)) <em class=\"markup--em markup--pre-em\"># id of y, different from x<\/em><\/pre>\n<p class=\"graf graf--p graf-after--pre\">Result:<\/p>\n<pre class=\"graf graf--pre graf-after--p graf--trailing\">\n<code class=\"markup--code markup--pre-code u-paddingRight0 u-marginRight0\">id of a: 1456621360\nx: 10\ny: 11\nid of x: 1456621344\nid of y: 1456621360<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>What is Python? Python is an\u00a0interpreted, interactive object-oriented programming language;\u00a0it\u00a0incorporated modules, classes, exceptions, dynamic typing and high level data types. Python is also powerful when it comes to clear syntax. It is a high-level general-purpose programming language that can be applied to many different classes of problems\u200a\u2014\u200awith a large standard library that encapsulates string processing [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":28127,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[40],"tags":[],"class_list":["post-28126","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-linux-freebsd-unix"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/28126","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=28126"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/28126\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media\/28127"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=28126"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=28126"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=28126"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}