E
E
Egor Tyuvaev2014-07-10 12:27:55
Python
Egor Tyuvaev, 2014-07-10 12:27:55

What does this passage from the Python documentation mean?

Statement: " ...strings ... are immutable. "
Full sentence: " An object's mutability is determined by its type; for instance, numbers, strings and tuples are immutable, while dictionaries and lists are mutable. "
I can't understand , which means " numbers and strings are immutable ". Why can't a string or number change its value?
The documentation itself

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Z
zed, 2014-07-10
@CulHatsker

Why can't a string or number change its value?

When you try to "change" the value of an immutable type, a new object will be created and assigned the new value. Those. outwardly, it will change, as it were, but “under the hood” objects will be created / destroyed, and not the same object will be changed (you know that in python even a simple int is an object?). And this behavior should be taken into account in order to write optimal code in which a bunch of objects will not be copied and destroyed in vain.
In view of this, in strings, for example, you cannot safely change individual characters, and you have to do strange things if you still need to change a character: Change one character in a string in Python?

I
iamnothing, 2014-07-10
@iamnothing

When they say mutable / immutable, they mean the object itself in memory, and not the variable symbol that is attached to this object. If I'm not mistaken, strings and numbers are immutable in most programming languages. For example, if there is a number 10 (not a variable!, but the number itself), then its value cannot be 0, or -99, or 55.64 - it is always equal to ten, and if you need another number in the variable, then you simply equate a variable to another number. It's the same with strings. For example, if concatenation occurs, then the result of the concatenation is a completely new object in memory, which you already assign to some variable. Those. any operations on strings produce new string objects in memory.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question