If strings are immutable, then how is this possible?
<p>I am new to python and was going through the python3 docs. In python strings are said to be immutable, then how is this possible:</p>

<pre><code>if __name__ == '__main__':
        l = 'string'
        print(l)
        l = l[:2]
        print(l)
</code></pre>

<p>returns this output:</p>

<pre><code>string
st
</code></pre>

<p>The key to understand this problem is to realize that variable in Python is just a "pointer" pointing to an underlying object. And you confused the concept of immutable object and immutable variable(which does not exist in Python).</p>

<p>For instance, in your case, <code>l</code> was initially a pointer pointing to a <code>str</code> object with content "string". But later, you "redirect" it to a new <code>str</code> object whose content is "st". Note that when the program runs to the line <code>l = l[:2]</code>, it's the pointer being modified, not the object pointed to by the pointer. If you will, you can also "redirect" <code>l</code> to another object with type other than <code>str</code>, say <code>l = 123</code>. Just remember, the original object pointed to by <code>l</code>(<code>str</code> "string") is not modified at all, it's still there in the memory(as long as it is not garbage collected), but just no longer pointed to by <code>l</code>.</p>

<p>For you to better understand the concept of immutable object, let's look at a mutable object. For example, <code>list</code> in Python is mutable. </p>

<pre><code>l = [1, 2, 3] # a new list with three elements
l.append(4) # append a new element 4 to the list (l is now modified!!!)
</code></pre>

<p>In the code above, we modified <code>l</code> by appending a new element to it. Throughout the program, <code>l</code> points to the same object, but it's the object pointed to by <code>l</code> that is changed in the process. </p>

python python-3.x immutability