0
Python - Why does list2[:] change list2's address?
list1 = [1,2,3] list2 = list1 print (hex(id(list1))) print (hex(id(list2))) list3 = list2[0:3] # Why does list2's address differ from list1's address here? print (hex(id(list1))) print (hex(id(list3)))
3 Respuestas
+ 4
It doesn't change list2's address at all. list3 is just a copy of list2 so it is a different object and so it has a distinct address.
0
A slice returns a new list
--> different object
--> different address
Whereas assignment statements in Python (ie. list2 = list1) do NOT copy objects
--> they create bindings between a target and an object
--> same address
0
A slice returns a new list containing the copied address of the objects stored in the original list. So slicing a list does not copy at all the objects inside it. But it effectively creates a new list.
But you're right : objects are very rarely copied, it is all references under the hood.
However, Python brings the concept of immuable object, meaning that any attempt to modify an attribut of this object create a new modified object, leaving the original one unchanged. There, it is effectively copy.