2

If a python string is immutable, how can it be changed as follows:

  a = "abc"
  print a
  a = "cde"
  print a

Outputs:

abc
cde

Is this actually creating a new variable and changed a to point to that instead?

0

3 Answers 3

5

Python strings are immutable. What you're doing is just reassigning the a variable with two different strings, that has nothing to do with immutability.

In the code shown no new variables are being created, there's just a. And in the assignments, a is pointed to a different string each time. To see that strings are immutable, take a look at this example:

a = 'abxde'
b = a.replace('x', 'c')

a
=> 'abxde'

b
=> 'abcde'

As you can see, a was not modified by the replace() method, instead that method created a new string, which we assigned to b, and that's where the replaced string ended. All string methods that perform changes are just like that: they don't modify the original string in-place, they create and return a new one.

3
  • I agree my understanding is in the wrong here - i am trying to learn though. How can i prove that the string is immutable in code Jun 23, 2013 at 21:51
  • Ok thanks - that now makes sense. Does the garbage collector pick up any old references after a was assigned to another string? Jun 23, 2013 at 21:56
  • It's possible, it depends on the implementation (whether it pools strings or not). Take a look at this answer. Jun 23, 2013 at 21:58
1
  • Yes, in Python, strings are immutable
  • Your code is not creating a new variable
  • Your code assigns the variable a a reference to another string
1

It's creating a new object and changing a to point to the new object.

Not the answer you're looking for? Browse other questions tagged or ask your own question.