0

I want to try to remove elements from a list without affecting the previous list.

This will give you a better picture:

>>> list_one = [1,2,3,4]
>>> list_two = list_one
>>> list_two.remove(2)
>>> list_two
[1, 3, 4]
>>> list_one  # <- How do I not affect this list?
[1, 3, 4]

Is there a workaround for this problem?

maverick97
  • 132
  • 2
  • 8
  • 3
    What makes you think you have two lists? (See [Facts and myths about Python names and values](http://nedbatchelder.com/text/names.html) by Ned Batchelder.) – Steven Rumbalski May 21 '14 at 16:13

1 Answers1

4

You need to make list_two a copy of list_one rather than a reference to it:

>>> list_one = [1,2,3,4]
>>> list_two = list_one[:]
>>> list_two.remove(2)
>>> list_two
[1, 3, 4]
>>> list_one
[1, 2, 3, 4]
>>>

Placing [:] after list_one creates a shallow copy of the list.

  • Ohhh I see. I was thinking list_two is a copy of it, not as a reference. :( Will try it now. – maverick97 May 21 '14 at 16:09
  • Thanks, works perfectly! Will accept your answer after the time limit. – maverick97 May 21 '14 at 16:10
  • @guanhao97: `[:]` makes a copy using [slice notation](http://stackoverflow.com/questions/509211/pythons-slice-notation). Another way to make a copy of `list_one` is to pass it to the list constructor `list(list_one)`. A third way is to use the `copy` module, which unnecessary when all you need is a shallow copy of a list. – Steven Rumbalski May 21 '14 at 16:23
  • Alright, reading the answers at the answered question also helped. Thanks. – maverick97 May 21 '14 at 16:25