0

I am currently writing a program but came across an error in the code. I got it down to this:

This is the basis of the problem:

original_list = ["a","b","c","d","e","f","g","h","i","j"]
value = "a"
new_list = original_list
print(original_list)
new_list.pop(new_list.index(value))
print(original_list)
print(new_list)

I would expect this to output:

['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
['b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

But instead it gives this, where the value "a" has been removed from the original list:

['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
['b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
['b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

I cannot seem to figure out why, does anyone know?

Joe Wilson
  • 77
  • 3
  • because that is how python works. you just give your list a new name. instead you want to make a (shallow) copy: `new_list = original_list[:]`. – hiro protagonist Dec 05 '18 at 12:07
  • `new_list = original_list` are names or references to the SAME underlying object. Lists are mutable. That means if you change the object using one of its methods, you have the ability to change the underlying object without changing the references. – Paritosh Singh Dec 05 '18 at 12:07
  • Mandatory reading: https://nedbatchelder.com/text/names.html – bruno desthuilliers Dec 05 '18 at 12:08

1 Answers1

0

When you write new_list = original_list, you are just making another name for the same old list.

If you want to really create a new list, you need to clone the old one. One way is to use new_list = list(original_list). The best way depends on the contents of the list.

André Laszlo
  • 15,169
  • 3
  • 63
  • 81