89085731
89085731

Reputation: 141

What mutable object really means in Python

I am quite confused about what mutable object really means

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

The print-out shows the same address, while for the following

A=[1,3,4]
print(id(A))
A=A+[1,2]
print(id(A))

The first thing is that it doesn't report wrong since I expect since it is mutable it will do the iterative procedure, on the other hand, the address is different.

Upvotes: 1

Views: 123

Answers (4)

Rajat Shenoi
Rajat Shenoi

Reputation: 760

Mutable objects means a data type that CAN CHANGE for example lists, dictionary, etcetera as you can always append or add values to them.

On the contrary, IMMUTABLE objects are those that CANNOT CHANGE, for example a TUPLE in python.

Hope it helped.

You must use .append() function

Upvotes: -1

Code-Apprentice
Code-Apprentice

Reputation: 83527

The first example mutates the list by calling append(). So the id() of the object is the same each time.

The second example reassigns the variable A to a new list that is the result of concatenating two lists. This does not mutate the original list. To see why, let's make a small modification:

A=[1,3,4]
print(id(A))
B=A+[1,2]
print(id(A))
print(id(B))

Now you will see that the id(A) is the same both times. Your original code is equivalent to this other than you no longer have a reference to the first list.

Upvotes: 1

Mahesh Anakali
Mahesh Anakali

Reputation: 344

A = [1,2,3]
A.append(4) #just appends new element to list (but does not create new memory address to A)
A = A + [5,6] # first do [1,2,3,4] + [5,6] => [1,2,3,4,5,6], then assign this to A (which is creating and assigning new memory address to A).

Upvotes: 0

Jarvis
Jarvis

Reputation: 8564

When you do

A = [1,2,3]
A.append(1)

you modify the list in place, thus causing no change in its address. On the other hand, when you do

A = [1,2,3]
A = A + [1,2]

you create a temporary new object A + [1,2] and then re-bind the existing list A to this newly created object (i.e. the newly created list), thus changing its address/id.

Upvotes: 3

Related Questions