+ 1

Explain this

a = [1,2,3,4] print(a is a[:]) #output: False (but why?)

24th Oct 2021, 2:45 AM
Fꫀⲅძ᥆͟ᥙ᥉᯽
Fꫀⲅძ᥆͟ᥙ᥉᯽ - avatar
2 Respuestas
+ 6
MD. Ferdous Ibne Abu Bakar "is" checks if both variable refer to the same object but a and a[:] would have different objects even both are looking same. Use == to check. use id() function to check identify of two objects print (id(a)) print (id(a[:])) will give different id
24th Oct 2021, 3:07 AM
A͢J
A͢J - avatar
+ 2
Hi Ferdous! If a is a name of the list then, a[:] is its shallow copy. It means when assigning, a (re)binds the name and a[:] slice-assigns, replacing what was previously in the list. For example, a = [1,2,3,4] a1 = a a2 = a[:] a1[0] = 0 print(a) #output: [0,2,3,4] print(a2) #output: [1,2,3,4] no changes So, both a,a1 are in a same location(same memory address), while a2 is in a different location. That's why print(a is a[:]) returns False.
24th Oct 2021, 3:34 AM
Python Learner
Python Learner - avatar