Statham Statham - 1 month ago 8
Python Question

Python: call a method of an object, when will the object will be changed and when will not?

I am new in python, and I just find something strange:

>>> test="acdefg"
>>> test.replace('a','h')
'hcdefg'
>>> test
'acdefg'
>>> test=[1,2,3]
>>> test.reverse()
>>> test
[3, 2, 1]


As you can see in the code, in the first time, variable "test" is a string, when I call method "replace", the value of "test" doesn't change, the second time is is a list, and the list changed after I called the method reverse().

Why was that? Is it because of something different between the methods or something different between the objects or something else?

Answer

Strings are immutable. So you aren't actually changing test. You are actually getting the return of the replace string method. To use this modified string, you have to create a new string, or simply replace the existing string with the new value.

>>> some_string = "abcd"
>>> new_string = some_string.replace('a', 'x')
>>> new_string
xbcd

>>> some_string = "abcd"
>>> some_string = some_string.replace('a', 'x')
>>> some_string
xbcd

The second example, the list is mutable, and you are performing an in place manipulation of the list. If you actually do this:

res = your_list.reverse()

res will actually be None, because it doesn't return anything, it actually does it in place, which is why test list will hold the new manipulation you performed.

Read this on immutable vs mutable types in Python.

Also, refer to the documentation here on the Data Model to further your understanding as well.

Comments