coderunner007 coderunner007 - 1 year ago 75
Python Question

If strings are immutable, then how is this possible?

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:

if __name__ == '__main__':
l = 'string'
l = l[:2]

returns this output:


Answer Source

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).

For instance, in your case, l was initially a pointer pointing to a str object with content "string". But later, you "redirect" it to a new str object whose content is "st". Note that when the program runs to the line l = l[:2], it's the pointer being modified, not the object pointed to by the pointer. If you will, you can also "redirect" l to another object with type other than str, say l = 123. Just remember, the original object pointed to by l(str "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 l.

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

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!!!)

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download