Wednesday, July 6, 2022

[FIXED] Why the modifications of a list inside a function do not change the list?

Issue

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)

Solution

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]


Answered By - Prune
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.