A
A
Artemy Kudryashov2021-06-26 10:59:06
Python
Artemy Kudryashov, 2021-06-26 10:59:06

Why do Python variables behave like this?

Why even when creating a new object and changing it, the first one also changes?
60d6de3c6e148018551252.png

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Sergey Gornostaev, 2021-06-26
@ez_l0l

Because you created a new list, but the dictionary in it remained the same.

Q
Quteray, 2021-06-26
@Qutray

The fact is that a variable is just a reference to an object that is in the cache.
In your code, both a and b have a link to the same memory department in which your list is located.
Thus, if you change a, the object it refers to will change, and since b also refers to this object, then when you output b, you will already have changed object.
To fix this situation, you need to use either the copy method or slices.

D
Dimonchik, 2021-06-26
@dimonchik2013

b = a[:]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question