0

I'm struggling to understand what the purpose of the empty slicing operator is in python

string_example = 'foo blah blah'
string_without_operator = string_example
string_with_operator = string_example[:]

print(string_without_operator)
print(string_with_operator)

In this example the results seem to be identical - are they functionally equivalent or am I missing something and this operator useful in a different application?

  • It is not doing anything useful that cannot be done without the operator. In the case of lists, a copy is made by slicing, which is a different object from the original list, and this can be important when it comes to mutating the list (e.g. assigning or adding elements) without disrupting the original. But strings are immutable in any case, so there is no useful gain in doing `mystring[:]` – alani Jun 25 '20 at 20:20
  • It creates a new string the entire length of the original. For strings that’s pretty pointless indeed, but for mutable objects like lists it’s an easy way to create a copy. – deceze Jun 25 '20 at 20:20
  • @deceze yes, and as a CPython implementation detail, empty slices on strings merely return the object itself. – juanpa.arrivillaga Jun 25 '20 at 20:33

0 Answers0