Mutable and Immutable Strings in python
Asked Answered
E

6

10

I was just going through mutable and immutable structures in python. It was written that "Strings are immutable" in Python i.e We cannot alter them Consider the code:

str1='Rohit'
str1.replace('R','M')

This gives the output:

'Mohit'

Now, somebody said that it is the variable str1 which is pointing to the string 'Rohit' and after str1.replace() it points to 'Mohit' Consider this code:

'Rohit'.replace('R','M')

This also gives me the output:

'Mohit'

Then what is meant by 'Strings are immutable'?

Edgington answered 14/11, 2017 at 14:0 Comment(4)
"somebody said that it is the variable str1 which is pointing to the string 'Rohit' and after str1.replace() it points to 'Mohit'" You can tell that someone that he's wrong. str1 will not change unless you do str1 = str1.replace(...), in which case it is assigned a new string, and the old one is discarded, but not changed.Tini
#9098494Wye
If you wanted to do str[0]="M" you would not be able to.Smutch
That += (ie. append) works is even more perplexing WRT "immutability".Tarn
S
22

Strings don't have any methods on them that allow a change to the value of the string. In other words: strings are immutable.

When you call str.replace a new string is built and returned.

>>> s1 = 'Rohit'
>>> s2 = s1.replace('R', 'M')
>>> 
>>> s1
'Rohit'
>>> s2
'Mohit'

As you can see s1 still has its original value.

Selfinductance answered 14/11, 2017 at 14:3 Comment(1)
>>>a='Rohit' >>> id(a) 52641584L >>> a=a.replace('R','M') >>> a 'Mohit' >>> id(a) 38710648L This cleared the confusionEdgington
L
7

Strings are known as Immutable in Python (and other languages) because once the initial string is created, none of the function/methods that act on it change it directly, they simply return new strings.

So, in your example

str1='Rohit'
str1.replace('R','M')

After the .replace call, you should try evaluating str1 in your REPL. It might surprise you to see that str1 still holds the value 'Rohit'. The .replace returns a new string in which all instances of the given character are replaced with the specified character. Your REPL will print that returned string, but after that it is lost since you didn't assign it to anything.

Your second example is much the same, but with a string constant instead of a variable like str1.

Lindo answered 14/11, 2017 at 14:6 Comment(0)
W
4

you can check mutability by checking id of variable before and after the change

In [3]: s1 = 'Rohit'

In [4]: id(s1)
Out[4]: 140510191375440

In [5]: s1.replace('R', 'M')
Out[5]: 'Mohit'

In [6]: id(s1)
Out[6]: 140510191375440
Wye answered 14/11, 2017 at 14:7 Comment(2)
That does not really check whether the string s1 is pointing to was changed, it merely checks whether it still points to the same instance.Tini
This is wrong. Simple counter-example: a dict is mutable, but the id stays the same, even after changing it.Biomedicine
D
3

Yes Python strings are immutable for sure. Lets suppose you have

s = "Rohit"

now s correctly points to the string object "Rohit". When you do something like

s.replace("R", "M")

this will not change s in place. The .replace method will replace "R" with "M" and then return the newly created object. In your case, it will be Mohit. Thats the reason you are able to see "Mohit" as a return value but its not changing s. Its creating a new string and returning that.

Discursive answered 5/10, 2020 at 8:9 Comment(0)
T
2

You are getting such output because that line of code does nothing to the string but creates a new string with R replaced with M (you can think it returned a variable), and in python when you simply type the name of a variale it is printed on the console. That's what created the confusion, I think.

Thralldom answered 14/11, 2017 at 14:22 Comment(0)
F
1

You can pass strings to functions which return a new string (as replace).

Strings don't have methods operating on themselves; we can try this, though:

>>> s1 = "abcd"
>>> s1[1:3]
'bc'
>>> s1[2]
'c'
>>> s1[2] = 'a'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

We can use subscripts on a string as if it were a list, but they are not writeable.

Footstall answered 8/7, 2022 at 10:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.