0

I'm having a very weird problem with my python now and I don't know if it's a bug or not.

When I have a list l = ["a", "b"],

And i assign that list to another variable:

other = l,

and then try to .remove or .pop something from other, l changes with it.

So if I were to do other.remove("a"), both other and l only contain ["b"], As if I was passing the list by reference.

Is this intended behavior?

David
  • 29
  • 1
  • This is the standard behavior of Python. `other` is a copy of the reference-to-list that `l` is - you didn't do a deep copy on the list. – wkl Aug 18 '17 at 15:02
  • 1
    Is it? I never knew that and I've been developing in python for quite some time now. huh – David Aug 18 '17 at 15:03
  • Assignment is always a reference in Python, never a copy. – Daniel Roseman Aug 18 '17 at 15:04
  • I'd usually just do other = l[:] instead of getting into deepcopy, but I'm not sure what the advantages of deepcopy are over that. – mauve Aug 18 '17 at 15:09
  • 1
    @mauve i[:] wont be good if there is a list of lists. The internal list will still be just a reference to the old one :) same if there is a list of dicts or any other iterable. – PYA Aug 18 '17 at 15:10
  • @pyjg I KNEW there was a reason there was a function for this. Thanks! That's something I've never specifically needed, and now I know to look out for it. – mauve Aug 18 '17 at 15:12
  • haha you are welcome, same issue if there is a class, see here https://repl.it/KPeJ – PYA Aug 18 '17 at 15:16

0 Answers0