Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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_:
        nums.append(i)
    print(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):
    print(False)
for i in range(k):
    if nums[i] != expectedNums[i]:
        print(False)
        print(nums, expectedNums)
        break

Output:

False
[1, 1, 2]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[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:

    nums.clear()

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!
    print(nums)
    return len(nums)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading