-3

https://leetcode.com/problems/reverse-string/ Hey there, I'm doing reverse the string on leetcode and this is the solution.

def reverseString(self, s):
    """
    :type s: List[str]
    :rtype: None Do not return anything, modify s in-place instead.
    """
    s[:] = s[::-1]

The part that I'm not understanding is s[:]. Why do we need that? From what I was thinking, we could simply do:

s = s[::-1]

Not understanding this and hoping someone could guide me. Thank you!

enzo
  • 9,861
  • 3
  • 15
  • 38
  • Note the comments in the posted code “.. modify s in-place instead”. What *different thing* would happen with a normal assignment? Also note that `s` is a *list of strings* (and the list can be modified), and it is not modifying an individual *string* “doing reverse the string” (which isn’t allowed, as strings are immutable). – user2864740 Oct 23 '21 at 05:39
  • 1
    [This answer](https://stackoverflow.com/a/57152896/15497888) addresses exactly this example complete with helpful info graphics. – Henry Ecker Oct 23 '21 at 05:45

1 Answers1

2

s = s[::-1] creates a new variable s and assigns it to the old variable s reversed, leaving the old s unchanged. s[:] = s[::-1] keeps the same old s variable and just mutates its contents with its reversed value. Basically,

def f1(s):
    s = s[::-1]

def f2(s):
    s[:] = s[::-1]


s = ["a", "b", "c"]

f1(s)
print(s)    # Outputs ["a", "b", "c"]

f2(s)
print(s)    # Outputs ["c", "b", "a"]
enzo
  • 9,861
  • 3
  • 15
  • 38
  • 1
    Thank you so much Enzo! This made perfect sense! – StudentProgrammer12 Oct 23 '21 at 07:04
  • In both cases it’s “the *same* variable”. While the official Python parlance might claim to “create a new binding”, *the effect for an existing local variable is to “assign a [different] object to the variable with the given name”* (https://ashtonkemerling.com/posts/binding-vs-assignment/). The call-by-object-sharing nature of Python secondarily explains why this assignment does not affect any bindings (re: variables) in the caller, even if the *same variable [as introduced by an parameter]* is re-assigned. – user2864740 Oct 23 '21 at 22:25