-1

I am writing a program to remove the duplicated elements from a given sorted list. I wrote function "removeDuplicates" to do some modifications on the list and print the updated list at the end of the function. Since the list is passed by reference, the question is why the changes do not apply on the list outside the function.

def removeDuplicates(nums):
    c = 0
    nums = nums + [nums[-1] + 1]  # add a dummy element to the end of the list
    for i in range(len(nums) - 1):
        if nums[i] != nums[i + 1]:
            nums[c] = nums[i]
            c = c + 1
    nums.pop()
    print(nums)

if __name__ == "__main__":
    nums = [1, 1, 1, 2, 2, 3, 4, 4, 4, 5, 5]
    removeDuplicates(nums)
    print(nums)
Mohsen
  • 3
  • 1

4 Answers4

3

Your problem is in the line:

nums = nums + [nums[-1] + 1]

because you are reassigning nums to a new value. Instead, try:

nums.append(nums[-1] + 1)

This way, you are changing the value of nums in place, which means that you're still referring to the same object throughout the function as opposed to creating a new object.

Toby Boyne
  • 31
  • 2
2
nums = nums + [nums[-1] + 1]  # add a dummy element to the end of the list

Wrong. You specifically create a new list from nums and your new element, and then make your local variable nums point to that new list. You then operate nicely on the new list and exit the function without saving the result.

Try

nums.append(nums[-1] + 1)  # add a dummy element to the end of the list

Output:

[1, 2, 3, 4, 5, 3, 4, 4, 4, 5, 5]
Prune
  • 76,765
  • 14
  • 60
  • 81
0

It's because if your second line in removeDuplicates:

nums = nums + [nums[-1] + 1]  # add a dummy element to the end of the list

This makes a new copy of the list parameter nums that was passed by reference, and your de-duping operations modify the copy instead of the original list.

Your function also has other issues, without that line I get the output:

>>> nums = [1, 1, 1, 2, 2, 3, 4, 4, 4, 5, 5]
>>> removeDuplicates(nums)
[1, 2, 3, 4, 2, 3, 4, 4, 4, 5]

Take a look at this excellent answer for better approaches: https://stackoverflow.com/a/7961390/11776945

evnp
  • 191
  • 1
  • 6
0

As mentioned in the other answers, the issue is when you are adding a dummy element. You are creating a new copy of nums variable. To avoid this, you can use the np.append() method suggested here or simply replace

nums = nums + [nums[-1] + 1]  

with

nums += [nums[-1] + 1]  

This way you will not be creating a new list.

Nebiyou Yismaw
  • 740
  • 4
  • 12