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]
0

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

3 Comments

Makes sense! Thank you so much for the details with images!
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 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.
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])

1 Comment

That worked!!! So I guess it doesn't really copy by assignment like nums = something.. I'm a bit confused.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.