0

I am currently working in Python 3. I would like to make some modifications to a list. So, I copied the original list(nums) to another list(nums1). When I am popping out any element from list nums1 then I am also loosing that element from nums. How do I make sure I am poppin an element only from one list.

nums = [1,2,3]
nums1 = nums
nums1.pop(1)
print(nums)
print(nums1)

output

[1, 3]
[1, 3]
Buddy Bob
  • 5,829
  • 1
  • 13
  • 44
santosh
  • 11
  • 3
  • 1
    `nums1 = nums` isn't doing what you think it's doing (probably). Check this out [List changes unexpectedly after assignment. Why is this and how to prevent it?](https://stackoverflow.com/questions/2612802/list-changes-unexpectedly-after-assignment-why-is-this-and-how-to-prevent-it) – Have a nice day May 09 '21 at 01:22
  • 1
    You are not really 'copying' the list. Use `nums.copy()` to do a real copying. – j1-lee May 09 '21 at 01:23
  • "So, I copied the original list(nums) to another list(nums1)." No you didn't, you didn't make a copy anywhere. There is a single list in your code, being referenced by two different variables. You should read the following: https://nedbatchelder.com/text/names.html – juanpa.arrivillaga May 09 '21 at 02:27

1 Answers1

1

I'm pretty sure it has something to do with referencing nums. To avoid this you can use .copy().

nums = [1,2,3]
nums1 = nums.copy()
nums1.pop(1)
print(nums)
print(nums1)

output

[1, 2, 3]
[1, 3]
Buddy Bob
  • 5,829
  • 1
  • 13
  • 44