Passing a mutable object to a function, we can modify its value without return. But if I pass a slice of a mutable object, seems that after running the function, the values of that object didn't change. Here is my code:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
s = list(str(x))
if s[0] == "-":
#if s=['-','1','2','3'], then s[1:]=['1','2','3'], after running self.reverseCore, s still is ['-','1','2','3']
print(id(s[1:]))
self.reverseCore(s[1:])
print(s)
else:
#if s=['1','2','3'], after running self.reverseCore, s will be['3','2','1']
self.reverseCore(s)
print(s)
def reverseCore(self, s):
print(id(s))
if len(s)<= 1:
return
l = len(s)
k = l//2
for i in range(0, k):
s[i], s[l-i-1] = s[l-i-1], s[i]
s[1:] is also a mutable object, then why it didn't change?