PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, July 6, 2022

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

 July 06, 2022     list, pass-by-reference, python     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing