0

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?

Lin.Chen
  • 73
  • 4

1 Answers1

0

How do you know that s[1:] didn't change? You never access it after the function returns. What you print is the original s, instead of the slice that you passed to the function.

Slicing creates a new list, and modifying the new list will have no effect on the original list.

This might be of interest to you: Reference to Part of List - Python

Roland Weber
  • 1,865
  • 2
  • 17
  • 27
  • Thanks for your answer. There is another thing that confused me: If slicing creates a new object, then s[1:]=something shouldn't modify s because s[1:] is a new object and it has nothing to do with s, but this case is not true and s will be changed. – Lin.Chen Jul 18 '19 at 06:56
  • Might be an optimization for the case where the slice is the full list. Please read up on slicing in the documentation. – Roland Weber Jul 18 '19 at 07:05