I have a look at python code where string variable assignments looks like:
var1 = var2[:]
I am just wondering what is the difference between:
var1 = var2
Here is my experiments:
>>> original = "some text"
>>> copy1 = original
>>> copy2 = original[:]
>>> original = "another text"
>>> copy1
'some text'
>>> copy2
'some text'
Updated:
Here is a full code. This code search a key for substitution cipher.
If I remove ‘[:]’ this code will works very slowly.
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
isoperator, which in contrast to the==operator checks wheter the actual memory address of the objects are the same: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:
But if
var2was some mutable sequential object, like alist, thenvar2[:]would be a shallow copy ofvar2, so that making changes to one would not affect the other.For the full picture, also read Ashwini Chaudharys answer.