Why is my list not updating outside the function? Aren't python lists called by assignment when passed in a function?

I’m not able to pass a lot of testcases for this problem. I ran the function as well as the code that the judge will use to test the function on my local machine and found out that the problem is that nums is not updated outside the function removeDuplicates() when it is is being called but it is updating within the function. Why is that? Aren’t python lists called by assignment when passed in a function?

def removeDuplicates(nums):
    nums_ = set(nums)
    nums = []
    for i in nums_:
    # not working even if I do nums = list(set(nums))
    return len(nums)

nums = [1,1,2]
expectedNums = [1,2]

k = removeDuplicates(nums)
if k != len(expectedNums):
for i in range(k):
    if nums[i] != expectedNums[i]:
        print(nums, expectedNums)


[1, 1, 2]

[1, 2]

Earlier I had used nums = list(set(nums)) instead of emptying the list and appending all unique elements but even that wasn’t working.

>Solution :

The line:

    nums = []

rebinds the local variable nums so that it no longer points to the list that was originally passed in, but to a newly created list.

If you instead do:


then you’re mutating the original list instead of creating a new one.

Just remember that the = operator rebinds a variable, rather than modifying the object that the variable refers to.

Obligatory Ned Batchelder link.

Note that a [] = subscript assignment also allows you to mutate a list (because you aren’t assigning a value to the variable, you’re assigning a value to an index or slice within the object that the variable refers to). You could write your function very simply as:

def removeDuplicates(nums):
    nums[:] = set(nums)  # you can slice-assign into a list from a set!
    return len(nums)

Leave a Reply