0

Why I am getting below behavior in python?

After assigning a in to b I am getting Boolean value "True".

>>> a = [[1,2],[3,4]]
>>> b = a
>>> a is b
True

And assigning with slicing operator I am getting Boolean value "False".

>>> b = a[ : ]
>>> a is b
False

and also Id of a and b changing if I am using slicing operator as below:

>>b = a[ : ] 
>>> id(b)
93006904
>>> id(a)
92963864
Rahul
  • 49
  • 6
  • How its is duplicate can you explain??. @jpp also that questions suggested by you, in that they are not talking about ID of references after doing copy using slicing operator. – Rahul Mar 17 '18 at 15:12
  • A copy will have a different id.. why would you expect it to have the same id? – jpp Mar 17 '18 at 15:17
  • @jpp why I am getting same Id when I will use >>b = a – Rahul Mar 17 '18 at 15:23
  • Because after the assignment `b = a` both names reference the same object. You should read https://nedbatchelder.com/text/names.html – Ilja Everilä Mar 17 '18 at 15:25
  • Thanks for Doc. @llija Everila. My question is why I am getting different reference ID if I am using slicing operator for assignment? – Rahul Mar 17 '18 at 15:30
  • Slicing creates an actual copy, a new list object. Assignment just gives names to things (a bit of an over simplification). – Ilja Everilä Mar 17 '18 at 15:35

1 Answers1

0

You can read b = a[:] as making a clone of a and naming the clone b.

Observe though that the cloning is done only at the outermost list:

>>> a = [[1,2], [3,4]]
>>> b = a[:]
>>> a is b
False
>>> a[0] is b[0]
True

That is, the contents of the a and b lists are references to the same object.

In Java you'd have b = a.clone() for Python's b = a[:].

Mihai Maruseac
  • 20,967
  • 7
  • 57
  • 109