Due to interning, there is often no difference (in the resulting object) between the two. We may check whether two variables point to the same object by using the is
operator, which in contrast to the ==
operator checks wheter the actual memory address of the objects are the same:
>>> a = "foo"
>>> b = a
>>> a is b
True
>>> c = a[:]
>>> a is c
True
Interning is a mechanism for saving memory and speeding up comparisons of immutable objects, and it works like this: before creating a new immutable, python checks to see if an identical immutable already exists. If so, it just uses a reference to the existing object. It can do that without harm because there's no way to change an immutable. This is why even two independently created strings may point to the same object:
>>> a = "foo"
>>> b = "foo"
>>> a is b
True
But if var2
was some mutable sequential object, like a list
, then var2[:]
would be a shallow copy of var2
, so that making changes to one would not affect the other.
>>> a = list("foo")
>>> a
['f', 'o', 'o']
>>> b = a
>>> b is a
True
>>> c = a[:]
>>> c is a
False
>>> b.pop()
'o'
>>> a
['f', 'o']
>>> b
['f', 'o']
>>> c
['f', 'o', 'o']
For the full picture, also read Ashwini Chaudharys answer.