0

I have a list, a = [1,2,3,4] from which I want to remove certain elements, say [2,4]. I also want to keep a copy of that list. So, the obvious way to do that is b = a and a.remove(2) and then a.remove(4). Turns out that the removed elements are also removed from b!!! Why???

The problem is more complicated that removing two known numbers - I find their indexes on the fly and then remove these, so I need the original data in order to know which index to check... Any help will be highly appreciated.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user3861925
  • 713
  • 2
  • 10
  • 24
  • Note that `list.remove` removes items by _value_, not index. If you know the index of an item that you want to remove, just use `del`. But rather than using `del` or `.remove` you might find it better to just build your new list by looping over the old list, copying items that match your criteria to the new list. This can be done in a traditional `for` loop, or using a list comprehension. – PM 2Ring May 04 '15 at 11:46
  • `b = a` does not make a copy of `a` and call it `b`. it only creates a pointer to `a` from `b`. instead you should try: `b = a[:]`. Also, iterating over a list and deleting indexes will cause trouble. if you really want to do this, I suggest going over it in reverse `for i in reversed(range(len(L))): if critea: del b[i]` or as @PM2Ring suggested, just build your new list in a for loop. – zazga May 04 '15 at 11:49
  • Hopefully, the info in the question that Martijn linked to is sufficient to explain why `b = a` doesn't make a new copy of the list bound to the name `a`. But for further info (with diagrams) on this important topic please see [Facts and myths about Python names and values](http://nedbatchelder.com/text/names.html) by SO member Ned Batchelder. – PM 2Ring May 04 '15 at 11:54

0 Answers0