Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list is not the same reference

Tags:

python

This is the code:

L=[1,2]

L is L[:]

False

Why is this False?

like image 977
Spì Avatar asked Mar 16 '10 10:03

Spì


2 Answers

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.

like image 175
Tim Pietzcker Avatar answered Oct 04 '22 00:10

Tim Pietzcker


When in doubt ask for id ;)

>>> li = [1,2,4]
>>> id(li)
18686240
>>> id(li[:])
18644144
>>> 
like image 23
Pratik Deoghare Avatar answered Oct 04 '22 02:10

Pratik Deoghare