Are Python strings truly immutable?

In summary: I... have... been... saying... strings... are... not... mutable. The operations that modify them, like string.replace(), actually create new string objects. In summary, the conversation discusses the concept of mutability in Python and how it applies to strings and integers. The speaker is using "Introducing Python" (Lubanovic) as a resource to learn Python and has come across the statement that Python strings are immutable. They express confusion about this concept and seek clarification on the difference between changing an int and changing a string in Python. The expert explains that both strings and integers are immutable in Python, but the way they are handled in the interpreter may create the illusion of mutability. They suggest reading the Python documentation for a better
  • #1
Grinkle
Gold Member
772
223
TL;DR Summary
Is it accurate to say that strings are immutable in Python?
I am using "Introducing Python" (Lubanovic) to teach myself Python.

I read that Python strings are immutable, then I see code like this -

string1 = 'base_val'
string1= 'new_val'

not throw up an error. A little investigation shows me that the interpreter created two strings and string1 is a pointer. This is all fine, and it has performance implications and it is important to understand, I get all that. 'base_val' was not necessarily destroyed when I changed the value of string1, the interpreter created a new string called 'new_val' and changed what string1 points to, and the literal 'base_val' was never changed.

Integers, on the other hand, are described as mutable. (edit: My mistake, the book correctly says that ints are also not mutable).

int1 = 3
int1 = 4

If Python were my first programming language, I'd be very confused about what 'immutability' is meant to imply. It seems to me that the immutability of Python strings is true in the context of the Python interpreter implementation code, not at all true in the context of a Python author's Python source code. There is no conceptual difference between the int code and string code above. At the level of Python functionality (which I distinguish from Python interpreter implementation) strings are mutable.

I looked on the internet to see if the author of my book is alone in describing Python strings as immutable, and he is not (I expected to find that, just noting so that no one thinks I am complaining about Lubanovic, I am not).

So, I think I am missing something - I am a couple decades past thinking I am smarter than the Python community after a couple days of self study. Can someone help me with a more pragmatic way of interpreting the statement that Python strings are immutable (rather than me dismissing this as not really relevant and a Python interpreter implementation thing, good to know but not really part of Python per se).

I do realize without surprise that some string modifications need to use string-object access functions and cannot be done directly, eg -

string1[2] = 'x'

throws and errror, I'd need to use string1.replace() after having found where in the string I want the x for instance, and for these kinds of string modifications there is a conceptual difference between changing an int and changing a string.

This is a part of Python per se, but to my thinking, it is how one changes strings in Python, which one can only do if strings are mutable.

Perhaps this is all about how to pronounce tomato, but I would really like to be more on the same page with the mainstream Python description of strings being immutable.
 
Last edited:
Technology news on Phys.org
  • #2
Grinkle said:
I read that Python strings are immutable, then I see code like this -

string1 = 'base_val'
string1= 'new_val'

not throw up an error.
That's because those two statements don't mean what they would mean in other language. Here is what is actually happening "under the hood" in the Python interpreter when those statements are executed:

Line 1: Create a string object with value "base_val" and bind it to the name "string1" in the current namespace.

Line 2: Create a string object with value "new_val" and bind it to the name "string1" in the current namespace.

In other words, "variables" in Python are not what they are in most other languages; they are not names for memory locations where data is stored. They are namespace bindings. (Under the hood, Python namespaces are just dictionary objects; the variable names like "string1" are the keys and the string objects like "base_val" and "new_val" are the values.)

This is one of the fundamental points about Python that it is very important to grasp in order to really understand how the language works. If the book you are using does not emphasize this point, I would say it's not a good book to be learning Python from.

Grinkle said:
'base_val' was not necessarily destroyed when I changed the value of string1, the interpreter created a new string called 'new_val' and changed what string1 points to, and the literal 'base_val' was never changed.
Yes, this is what I was saying above. But you might not have fully considered the implications.

Grinkle said:
Integers, on the other hand, are described as mutable.
If your book says this then your book is simply wrong. Integer objects in Python are immutable, just like strings.

I strongly suggest reading the Python documentation if you want to learn more about how the language works. The page on the data model describes which types of objects are immutable and which are mutable:

https://docs.python.org/3/reference/datamodel.html

Note in particular the statement under the "numbers.Number" heading that "Numeric objects are immutable". That includes not only ints but booleans, floats, and complex numbers, as you will see if you read on from that point.

Grinkle said:
I think I am missing something
No, your book's author is simply making a wrong claim about Python integers. See above. Your intuitive sense that, since the same kind of code works the same way for ints and strings, ints should be immutable just like strings are, is correct.

Grinkle said:
I do realize without surprise that some string modifications need to use string-object access functions and cannot be done directly, eg -

string1[2] = 'x'

throws and errror
Yes, this is one consequence of strings being immutable.

Grinkle said:
I'd need to use string1.replace()
And even that would not modify the existing string object in place, it would create a new string object, and you would have to bind that new string object to a variable to be able to use it. Consider this:

Python:
>>> string1 = "This is a string."
>>> string1.replace("a", "b")
'This is b string.'
>>> string1
'This is a string.'
>>> string2 = string1.replace("a", "b")
>>> string1
'This is a string.'
>>> string2
'This is b string.'

Notice how when string1.replace was called without assigning to a variable, the interpreter printed out the result, but then it got thrown away; string1 remained the same as before. To capture the result for future use, we had to assign it to a new variable.

Grinkle said:
to my thinking, it is how one changes strings in Python, which one can only do if strings are mutable.
As the above shows, you are not changing the string, you are creating a new one. All "operations" on immutable objects in Python work this way.
 
  • Informative
  • Like
Likes Wrichik Basu, Grinkle and FactChecker
  • #3
Grinkle said:
Summary: Is it accurate to say that strings are immutable in Python?
Yes.

Grinkle said:
Integers, on the other hand, are described as mutable.
No, integers (and floats) are immutable too.

Grinkle said:
Can someone help me with a more pragmatic way of interpreting the statement that Python strings are immutable.
Mutable objects have methods which mutate them e.g. the append method of a List. No such methods exist for a string (or other primitive type).
 
  • #4
Integers and floats are not objects. They are primitive types. As such they are not "immutable objects". When we say "immutable" we usually mean objects. A string _is_ an object.
 
  • #5
I like Serena said:
Integers and floats are not objects. They are primitive types. As such they are not "immutable objects". When we say "immutable" we usually mean objects. A string _is_ an object.
From: https://docs.python.org/3.6/reference/datamodel.html
The value of some objects can change. Objects whose value can change are said to be mutable; objects whose value is unchangeable once they are created are called immutable. (The value of an immutable container object that contains a reference to a mutable object can change when the latter’s value is changed; however the container is still considered immutable, because the collection of objects it contains cannot be changed. So, immutability is not strictly the same as having an unchangeable value, it is more subtle.) An object’s mutability is determined by its type; for instance, numbers, strings and tuples are immutable, while dictionaries and lists are mutable.
 
  • Informative
  • Like
Likes Grinkle and I like Serena
  • #6
I like Serena said:
Integers and floats are not objects.
In Python, they are. This thread is about Python, not C or other similar languages.
 
  • Like
Likes I like Serena
  • #7
PeterDonis said:
Your intuitive sense that, since the same kind of code works the same way for ints and strings, ints should be immutable just like strings are, is correct.

My mistake - Lubanovic does correctly list the basic types and their mutability, I was wrong in my initial post. So I am more comfortable now that the descriptions are consistent. Thanks for the detailed responses, everyone. Just the context I was asking for.
 
  • Like
Likes I like Serena
  • #8
I like Serena said:
Integers and floats are not objects. They are primitive types. As such they are not "immutable objects". When we say "immutable" we usually mean objects. A string _is_ an object.
Everything in Python is an object, although it is true that this is more an implementation detail than part of the specification of the language.
 
  • #9
pbuk said:
Everything in Python is an object, although it is true that this is more an implementation detail than part of the specification of the language.
No, it's part of the Python language. See the first two sentences of the "Data Model" page from the Python language reference, already linked to in this thread.
 
  • Like
Likes pbuk and FactChecker
  • #10
PeterDonis said:
No, it's part of the Python language. See the first two sentences of the "Data Model" page from the Python language reference, already linked to in this thread.
That's good. It would be criminal if the things that are discussed in this thread were not standardized by the language and were dependent on the implementation.
 
  • #11
In my experience, a lot of writers and teachers are not very good at teaching object oriented programming. For Python, I would highly urge you to check out Dave Matuszek's small book "I Guess We're Doing Python Now". Matuszek is the best professor I ever had for programming. He taught for decades and was revered, and in his retirement, he's writing books.

https://www.amazon.com/dp/1951998065/?tag=pfamazon01-20
 
  • Like
Likes Wrichik Basu

1. What are immutable objects in Python?

In Python, an immutable object is an object whose value cannot be changed after it is created. Examples of immutable objects in Python include strings, numbers, and tuples.

2. Are Python strings truly immutable?

Yes, Python strings are truly immutable. This means that once a string is created, it cannot be modified. Any operation that would change the value of a string actually creates a new string object.

3. Why are strings immutable in Python?

Strings are immutable in Python for efficiency and security reasons. By making strings immutable, Python avoids the overhead of constantly copying and modifying string objects. This also helps to prevent unintended changes to sensitive data.

4. What are the advantages of using immutable strings?

Immutable strings in Python offer several advantages, including improved performance, easier debugging, and better memory management. They also prevent unexpected changes to data, which can be critical in certain applications.

5. Can you give an example of how to create an immutable string in Python?

Yes, an example of creating an immutable string in Python is using the string literal syntax, such as 'Hello World'. This creates a string object that cannot be modified. Another way to create an immutable string is by using the str() function, which converts any object into a string.

Similar threads

Replies
6
Views
1K
  • Programming and Computer Science
Replies
3
Views
318
  • Programming and Computer Science
Replies
4
Views
1K
  • Programming and Computer Science
Replies
5
Views
1K
  • Programming and Computer Science
Replies
18
Views
2K
  • Programming and Computer Science
Replies
3
Views
891
  • Programming and Computer Science
Replies
31
Views
6K
  • Programming and Computer Science
Replies
15
Views
2K
  • Programming and Computer Science
Replies
5
Views
9K
  • Programming and Computer Science
Replies
6
Views
3K
Back
Top