0

So this is happening:

a = [1,2]
b = a
b += [3]
print(a)

[1, 2, 3]

It's extremely confusing and it's screwing up my project's test suite, which takes a list of strings and tests that it gets modified in the correct ways by each function.

Did I just find a bug in Python, or is there some convoluted reason for this misbehavior?

yatu
  • 86,083
  • 12
  • 84
  • 139
  • 1
    Does this answer your question? [How to clone or copy a list?](https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list) – Asocia Jun 12 '20 at 13:15
  • What misbehavior? `a` and `b` are names referring to a single list. Make a copy - `b = a.copy()` or `b = a[:]` - if you want a second list that can be modified separately. – jasonharper Jun 12 '20 at 13:16
  • This is not a bug nor misbehaviour. This is a fundemental principle in Python which is that variables are merely refereneces to objects and many variables can reference to the same object, which is what happens here. I think you should read some tutorials on Python variables and references – Tomerikoo Jun 12 '20 at 13:16
  • 1
    Relevant: https://stackoverflow.com/questions/52747784/is-i-i-n-truly-the-same-as-i-n/52747886 – timgeb Jun 12 '20 at 13:17
  • `+=` for lists secretly does `extend` (an inplace operation), not `lst = lst + ...`. – timgeb Jun 12 '20 at 13:18
  • Ok but why? With the singular purpose to frustrate beginners? – openSourcerer Jun 12 '20 at 13:23
  • Now I have to question every piece of python code I've ever written... Trace back every a = b, b = c, c = d, d+=1, I don't even know what's real anymore – openSourcerer Jun 12 '20 at 13:26
  • Even passing variables as function arguments edits the variable in place in the global scope, I can't imagine one case where that wouldn't silently screw things up – openSourcerer Jun 12 '20 at 13:31

0 Answers0