0

I'm trying to remove item "a" from list nm but not from list name but some how remove function deletes it from both the lists. Please Help!

I've tried using del function instead too, no success.

>>> name=["a","b","c"]
>>> nm=name
>>> nm.remove("a")
>>> nm`enter code here`
['b', 'c']
>>> name
['b', 'c']

I was expecting the name list to remain as ["a","b","c"] at the end.

1 Answers1

1

This is because name is a reference to a list. nm=name is just creating a new variable which points to the same list. You need to explicitly copy the list so that there are two in memory if you want them to be different.

change

nm=name

to

nm=name[:]

This tells python to do a shallow copy of the list instead of copying the reference. There are many ways to do this, I think this is the easiest (for lists) as it involves minimal edits and no imports. You can also use the copy module which is in the Python standard library if you want to achieve the same thing for other data types.

Tom Lubenow
  • 1,109
  • 7
  • 15