Python modify/change reference value with assignment in function

Question:

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]
Asked By: redpotato

||

Answers:

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

Answered By: Dorian Turba

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])
Answered By: Mureinik
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.