Python list is not the same reference
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
精彩评论