Python - Why does list2[:] change list2's address? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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)))

25th Oct 2020, 9:08 PM
Solus
Solus - avatar
3 Answers
+ 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.
25th Oct 2020, 9:11 PM
Russ
Russ - avatar
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
25th Oct 2020, 9:35 PM
Solus
Solus - avatar
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.
25th Oct 2020, 10:59 PM
Théophile
Théophile - avatar