开发者

Python list is not the same reference

开发者 https://www.devze.com 2022-12-23 05:27 出处:网络
This is the code: 开发者_运维知识库 L=[1,2] L is L[:] False Why is this False?L[:] (slice notation) means: Make a copy of the entire list, element by element.

This is the code:

开发者_运维知识库
L=[1,2]

L is L[:]

False

Why is this False?


L[:] (slice notation) means: Make a copy of the entire list, element by element.

So you have two lists that have identical content, but are separate entities. Since is evaluates object identity, it returns False.

L == L[:] returns True.


When in doubt ask for id ;)

>>> li = [1,2,4]
>>> id(li)
18686240
>>> id(li[:])
18644144
>>> 


The getslice method of list, which is called when you to L[], returns a list; so, when you call it with the ':' argument, it doesn't behave differently, it returns a new list with the same elements as the original.

>>> id(L)
>>> id(L[:])
>>> L[:] == L 
True
>>> L[:] is L
False
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号