When there are A and B with type list in Python (or even if type is not list)
If you declare A = B and touch A afterwards, does B change as well?
Also, in order to keep B unchanged, should I declare A <-B instead of A = B?
I just turned my code, but I've never put B on the left (left side of the equal sign) and I only touched A, but I think B has changed.
python
Think of Python's variable as basically storing addresses
>>> a = [1,2,3]
>>> b = a
If so, a stores an address value that can refer to [1,2,3]
and b stores the same address value that is stored in a.
Therefore, if you work with a.append(4)
, b stores the same address value as a, so if you output a
and b
, you will get [1, 2, 3, 4]
.
>>> a = [1, 2, 3]
>>> b = a
>>> a = [1, 2, 3, 4]
If you do it as above, b stores the address value that a previously pointed to, but a stores the new address value, so the two exist separately.
If you want to distinguish between a
and b
in a universal situation including a list, you can do the following.
import copy
a = [1, 2, 3]
b = copy.deepcopy(a)
>>> a
[1, 2, 3]
>>> b
[1, 2, 3]
>>> a.append(4)
>>> a
[1, 2, 3, 4]
>>> b
[1, 2, 3]
Summary: Python does not have a <-
operator, but you probably misread the <
and the negative sign -
If you declare A = B and touch A afterwards, does B change as well?
Yes.
Many use methods such as A = B[:]
to create and assign replicas using full slicing.
© 2024 OneMinuteCode. All rights reserved.