-1

Thank you for your valuable time, I have just started learning Python. I came across Mutable and Immutable objects. As far as I know mutable objects can be changed after their creation.

a = [1,2,3]
print(id(a))
45809352
a = [3,2,1]
print(id(a))
52402312

Then why id of the same list "a" gets changed when its values are changed.

3

5 Answers 5

5

your interpretation is incorrect.

When you assign a new list to a, you change its reference.

On the other hand you could do:

a[:] = [3,2,1]

and then the reference would not change.

Sign up to request clarification or add additional context in comments.

Comments

0

mutable means that the content of the object is changed. for example a.append(4) actually make a equal to [1, 2, 3, 4], while on the contrary, appending to a string (which is immutable) does not change it, it creates a new one.

However, when you re-assign, you create a new object and assign it to a, you don't alter the existing content of a. The previous content is lost (unless refered-to by some other variable)

2 Comments

You comparison to "appending to a string" is not so good, because a string does not have an append method. You can only do string + "foo", which will create a new string, but so does [1,2,3] + [4]. str.replace might be a better example.
@tobias_k: ok, did not mean it literally, just wanted to convey the idea. In other languages there is an append, but still the main idea it the creation of a new object
0

If you change a list, its id doesn't change. But you may do things that instead create a new list, and then it will also have a new id.

E.g.,

>>> l=[]
>>> id(l)
140228658969920
>>> l.append(3)  # Changes l
>>> l
[3]
>>> id(l)
140228658969920  # Same ID
>>> l = l + [4]  # Computes a new list that is the result of l + [4], assigns that
>>> l
[3, 4]
>>> id(l)
140228658977608  # ID changed

Comments

0

When you do

a = [3, 2, 1]
  1. You unlink the list of [1, 2, 3] from variable a.
  2. Create a new list [3, 2, 1] then assign it to a variable.

Comments

0

Being immutable doesn't mean you assign a new object, it means your original object can be changed "in place" for example via .append()

>>> my_list = [1,2,3]
>>> id(my_list)
140532335329544
>>> my_list.append(5)
>>> id(my_list)
140532335329544
>>> my_list[3] = 4
>>> my_list
[1, 2, 3, 4]
>>> id(my_list)
140532335329544

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.