Sobes.tech
Junior — Middle

How does changing the content of a mutable object affect its further use?

sobes.tech AI

Answer from AI

In Python, mutable objects (such as lists, dictionaries, sets) retain their identity (id) when their contents are changed, meaning they are modified "in place." This implies that if multiple variables reference the same object, changes made through one variable will be visible through others.

For example:

lst = [1, 2, 3]
alias = lst
lst.append(4)
print(alias)  # Will output: [1, 2, 3, 4]

It's important to consider this to avoid unexpected side effects. If you need to preserve the original object, you should create a copy (for example, using list.copy() or the copy module).

Unlike mutable objects, immutable objects (such as strings, tuples) create a new object when "changed."