in Lists –
I can always check that b=a points to same object and c=a[:] creates another copy.
>>> a = [1,2,3,4,5]
>>> b = a
>>> c = a[:]
>>> a[0] = 10
>>> b
[10, 2, 3, 4, 5]
>>> c
[1, 2, 3, 4, 5]
In Strings –
I cannot make a change to the original immutable string. How do I confirm myself that b=a makes b point to same object, while c = a[:] creates a new copy of the string?
you can use the
isoperator.This works because
a is bif and only ifid(a) == id(b). In CPython at least,id(foo)is just the memory address at whichfoois stored. Hence iffoo is bar, then foo and bar are literally the same object. It’s interesting to note thatis
True. This is because python interns (at least most) strings so that it doesn’t waste memory storing the same string twice and more importantly can compare strings by comparing fixed length pointers in the C implementation instead of comparing the strings byte by byte.