Numeric Literal are immutable (unchangeable)

Dear All,
I read the statement from the Python documentation that Numeric Literal is immutable. Can anyone explain this with an example.

Thanks & Regards
Saravanan Shanmugham

Consider the following:

var_integer = 100
var_string = "This is a string"

100 is a numeric literal. It represents an atomic value of 100.
var_integer is a variable of integer type.
A variable can hold any value of that particular data type.
Can we modify the literal 100 to represent another value, say 1000? The answer is No.
Hence literals are immutable.

Same explanation holds good for string literal as well, in fact it is true for any literal.

2 Likes

Very nice explanation…:slight_smile:

Thanks for the response. As you said all literals are immutable. It is obvious that variable is updated with different literal, but same literal cannot be changed.

What would be an example for mutable object.

Conceptually speaking, in the above example, var_integer, var_string are mutable objects.
They are mutable because they can be modified.

But it depends on programming language.

In Python -
objects of type List, Dictionary, Set and user defined classes are mutable.
objects of type Int, float, bool, string, tuple and range are immutable.

list_obj = [1,2,3]
print(id(list_obj))
list_obj.append(4)
print(id(list_obj))

Notice that the reference do not change.

Whereas,

int_obj = 10
print(id(int_obj))
int_obj+=1
print(id(int_obj))

a change in reference can be seen here.

Hope this helps.