I am just learning python and I am going though the tutorials on https://developers.google.com/edu/python/strings
Under the String Slices section
s[:] is ‘Hello’ — omitting both always gives us a copy of the whole
thing (this is the pythonic way to copy a sequence like a string or
list)
Out of curiosity why wouldn’t you just use an = operator?
s = 'hello';
bar = s[:]
foo = s
As far as I can tell both bar and foo have the same value.
=makes a reference, by using[:]you create a copy. For strings, which are immutable, this doesn’t really matter, but for lists etc. it is crucial.but:
So why use it when dealing with strings? The built-in strings are immutable, but whenever you write a library function expecting a string, a user might give you something that “looks like a string” and “behaves like a string”, but is a custom type. This type might be mutable, so it’s better to take care of that.
Such a type might look like:
Disclaimer: This is just a sample to show how it could work and to motivate the use of
[:]. It is untested, incomplete and probably horribly performant