Immutable Python strings

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
766
213
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

What are immutable Python strings?

Immutable Python strings refer to strings that cannot be modified or altered after they have been created. This means that once a string object is created, its value cannot be changed.

Why are Python strings immutable?

The immutability of Python strings is a design choice made by the creators of the language. This ensures data integrity and makes strings easier to work with, as they are always in a consistent state. It also allows strings to be used as keys in dictionaries and as elements in sets.

How are immutable strings different from mutable strings?

Mutability refers to the ability of an object to be modified after it has been created. Immutable strings cannot be modified, while mutable strings can be changed without creating a new object.

Are there any advantages to using immutable strings?

Yes, there are several advantages to using immutable strings. They are more memory efficient, as they can be cached and reused. They also make code more predictable and easier to debug, as the value of a string will never change unexpectedly.

Can immutable strings be changed at all?

No, immutable strings cannot be changed. However, it is possible to create a new string object with a modified value based on the original string. This is known as string concatenation.

Suggested for: Immutable Python strings

Replies
2
Views
500
Replies
1
Views
1K
Replies
3
Views
865
Replies
2
Views
846
Replies
6
Views
986
Replies
24
Views
1K
Replies
1
Views
735
Replies
2
Views
935
Back
Top