Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aren't Python strings immutable? Then why does a + " " + b work?

My understanding was that Python strings are immutable.

I tried the following code:

a = "Dog" b = "eats" c = "treats"  print a, b, c # Dog eats treats  print a + " " + b + " " + c # Dog eats treats  print a # Dog  a = a + " " + b + " " + c print a # Dog eats treats # !!! 

Shouldn't Python have prevented the assignment? I am probably missing something.

Any idea?

like image 611
jason Avatar asked Feb 01 '12 14:02

jason


People also ask

Are python strings immutable?

In Python, strings are made immutable so that programmers cannot alter the contents of the object (even by mistake).

Are strings in python mutable or immutable?

In python, the string data types are immutable. Which means a string value cannot be updated.

What if string is not immutable?

The String is immutable, so its value cannot be changed. If the String doesn't remain immutable, any hacker can cause a security issue in the application by changing the reference value. The String is safe for multithreading because of its immutableness.

Does using the += operator to concatenate strings violate python's string immutability Why or why not?

It violates the rules of how ID values and += are supposed to work - the ID values produced with the optimization in place would be not only impossible, but prohibited, with the unoptimized semantics - but the developers care more about people who would see bad concatenation performance and assume Python sucks.


2 Answers

First a pointed to the string "Dog". Then you changed the variable a to point at a new string "Dog eats treats". You didn't actually mutate the string "Dog". Strings are immutable, variables can point at whatever they want.

like image 117
Bort Avatar answered Oct 12 '22 12:10

Bort


The string objects themselves are immutable.

The variable, a, which points to the string, is mutable.

Consider:

a = "Foo" # a now points to "Foo" b = a # b points to the same "Foo" that a points to a = a + a # a points to the new string "FooFoo", but b still points to the old "Foo"  print a print b # Outputs:  # FooFoo # Foo  # Observe that b hasn't changed, even though a has. 
like image 35
Sebastian Paaske Tørholm Avatar answered Oct 12 '22 11:10

Sebastian Paaske Tørholm