1

I'm trying to change the referenced value nums in removeDuplicates function. So after the function is called, test can have [1, 2, 3, 4, 5]. But the result is test still have [9, 8, 7, 6]. Is there a way modify with assignment?

class Simple:
    def removeDuplicates(self, nums: List[int]) -> int:
        nums = [1, 2, 3, 4, 5]
        print("in function: ", nums)

simple = Simple()
test = [9, 8, 7, 6]
simple.removeDuplicates(test)
print("after function: ", test)
Result: 
in function:  [1, 2, 3, 4, 5]
after function:  [9, 8, 7, 6]
redpotato
  • 142
  • 1
  • 2
  • 15

2 Answers2

2

Don't rebind, mutate

nums is a reference to a list, but if you reassign a new value, you will change the ref to another value in memory. See more information about how python pass by assignment.

TLDR: in the function, nums is a ref to the original list, but if you assign a new value, you don't change the "memory", you create a new ref and loose access to the old memory space.

See:python tutor

class Simple:
    def removeDuplicates(self, nums: list[int]) -> int:
        nums.clear()
        nums.extend([1, 2, 3, 4, 5])
        print("in function: ", nums)


simple = Simple()
test = [9, 8, 7, 6]
simple.removeDuplicates(test)
print("after function: ", test)

# in function:  [1, 2, 3, 4, 5]
# after function:  [1, 2, 3, 4, 5]

With this version, at the end of the function, nums still point to the same list as outside test: python tutor

Dorian Turba
  • 3,260
  • 3
  • 23
  • 67
  • 1
    Makes sense! Thank you so much for the details with images! – redpotato Feb 10 '23 at 17:12
  • Sorry, I now have one more question.. what about string type or integer when it passed as a reference value? Since = assignment will not work, is there a way to override them simple way like list object? or it's not possible in Python? – redpotato Feb 10 '23 at 19:12
  • @redpotato It's not possible since this types of value are immutable. But, if this values are stored in a dict or a custom object that allows set of its attributes, you can by mutating the object itself like `dict_[key] = 'new_str'`. Since the dict is the namespace used to access the value, you will be able to get this new value from an outer scope. – Dorian Turba Feb 10 '23 at 20:18
1

As you've seen, you can't overwrite a variable's reference like that.

What you could do, however, is clear the original list and then append the values you wanted to it so you keep the original reference, but change the content of the list:

nums.clear()
nums.extend([1, 2, 3, 4, 5])
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • That worked!!! So I guess it doesn't really copy by assignment like nums = something.. I'm a bit confused. – redpotato Feb 10 '23 at 16:29