The shallow copy of Python and the problem of is

>>> names = [1,2,3]
>>> names = [1,2,[3,4]]
>>> n = names.copy()
>>> n is names
False
Is

is the memory address stored in the comparison variable? In that case, shouldn"t the memory addresses stored in n and names be the same?
this knowledge point has not been understood.
ask for help.

Mar.09,2021

is compares whether two variables point to the same object, copy () and generates a new object, so is returns False


(1) is compares whether two references point to the same object (reference comparison).

clipboard.png

ab:

clipboard.png

2 ncopy

"b = a" n = names.copy()

:

:

clipboard.png

:

clipboard.png

:
1a,b
2c,c[0],c[1]a,b
3"e = c.copy()":,c[0],c[1],c[0],c[1]
4ee[0],e[1])a,b.ece,cec.copy()isFalse.:

clipboard.png

probably explain this, small students are not talented, speech skills may not be very difficult, I hope I can help you.



>>> a = 1
>>> names = [a]
>>> n = names.copy()
>>> n is names
False
>>> n[0] is names[0]
True
Shouldn't the memory addresses stored in
n and names be the same?

first of all, make it clear that you want to compare n and names, or the internal elements of the two.

names opens up memory space for n because it is a list (mutable), copy operation, so here n and names are compared to False with is.

and the copy case of another immutable:

>>> import copy
>>> a = (1, 2)
>>> copy.copy(a) is a
True
Menu