Spì
Spì

Reputation: 2255

Python list is not the same reference

This is the code:

L=[1,2]

L is L[:]

False

Why is this False?

Upvotes: 6

Views: 315

Answers (3)

dalloliogm
dalloliogm

Reputation: 8940

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

Upvotes: 2

Pratik Deoghare
Pratik Deoghare

Reputation: 37172

When in doubt ask for id ;)

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

Upvotes: 6

Tim Pietzcker
Tim Pietzcker

Reputation: 336108

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.

Upvotes: 14

Related Questions