Shallow copy of list[:]

zch*_*kui 5 python copy

According to this Official Documentation:

list[:]
Run Code Online (Sandbox Code Playgroud)

creates a new list by shallow copy. I performed following experiments:

>>> squares = [1, 4, 9, 16, 25]
>>> new_squares = square[:]
>>> squares is new_squares
False
>>> squares[0] is new_squares[0]
True
>>> id(squares)
4468706952
>>> id(new_squares)
4468425032
>>> id(squares[0])
4466081856
>>> id(new_squares[0])
4466081856
Run Code Online (Sandbox Code Playgroud)

All here look good! new_square and square are different object (list here), but because of shallow copy, they share the same content. However, the following results make me confused:

>>> new_squares[0] = 0
>>> new_squares
[0, 4, 9, 16, 25]
>>> squares
[1, 4, 9, 16, 25]
Run Code Online (Sandbox Code Playgroud)

I update new_square[0] but square is not affected. I checked their ids:

>>> id(new_squares[0])
4466081824
>>> id(squares[0])
4466081856
Run Code Online (Sandbox Code Playgroud)

You can find that the id of squares[0] keeps no change but the id of new_squares[0] changes. This is quite different from the shallow copy I have understood before.

Could anyone can explain it? Thanks!

Fre*_*chy 0

列表是可变的,整数是不可变的

当你这样做时:

squares = [1, 4, 9, 16, 25]
new_squares = square[:]
Run Code Online (Sandbox Code Playgroud)

squares 和 new_squares 有不同的 id

如果你这样做:

[id(squares[i]) for i in range(len(squares))]
[id(new_squares[i]) for i in range(len(new_squares))]
Run Code Online (Sandbox Code Playgroud)

您将看到每个整数都有相同的 id。如果用另一个值修改整数,则该整数将有一个新的 id