0
#create list
listA = [1,2]
#'duplicate' list
listB = listA
#remove item in 'duplicate'
listB.remove(1)
#item has been removed from listA even though it hasn't been edited
print(listA)
# Result: [2]

Logically I would assume that listA would not get edited. Since I'm not directly editing it. So if python points to locations of variable 'contents' then I can understand it. Since listB would not be a true 'duplicate' but another 'sign post' pointing to the same set of information. But if thats true, then why:

#

create variable
intA = 5
#'duplicate' variable
intB = intA
#chane item in 'duplicate'
intB = 0
#item has NOT been removed from listA because it hasn't been edited
print( 

intA )

Lens
  • 19
  • 4
  • 1
    Because assignment *never copies* and *never mutates*. An assignment just says "the name on the left hand side now refers to the object on the right hand side". Both of these examples are perfectly consistent. You should read https://nedbatchelder.com/text/names.html – juanpa.arrivillaga Feb 14 '20 at 12:06
  • Does this answer your question? [List of lists changes reflected across sublists unexpectedly](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) – h4z3 Feb 14 '20 at 12:07
  • @h4z3 that duplicate has nothing to do with this. – juanpa.arrivillaga Feb 14 '20 at 12:07
  • Note, *mutability is irrelevant here*. You can use lists and see the same behavior, so `listA = []; listB = listA; listB = ['foo']; print(listA)` will print `[]` – juanpa.arrivillaga Feb 14 '20 at 12:08
  • @juanpa.arrivillaga Read the answer in the linked question and say this again. Your example is wrong, you literally overwrite listB in it. Do `listB.append('foo')` and say this again. This IS mutability issue – h4z3 Feb 14 '20 at 12:09
  • @h4z3 the answer in the linked question is about the semantics of the *repetition operator*, this is about the semantics of the *assignment statement*. Two unrelated things. And the semantics of assignment *is the same regardless of the type of object*, so mutable and immutable objects work *exactly the same* when it comes to assignment. The example I'm giving is reproducing the behavior that the OP is seeing with `int` objects, which happen to be immutable, with `list` objects, which are mutable. Of course, you *cannot mutate immutable objects* – juanpa.arrivillaga Feb 14 '20 at 12:12
  • @juanpa.arrivillaga The problem showed is more complex, yes, but it all boils down to mutability - which you deny. I chose first link that appeared in my search, but here's a better one - https://stackoverflow.com/questions/53055087/python-list-mutable This still doesn't change the fact that this question is a duplicate and you should report it (like I did, but maybe with this better link). – h4z3 Feb 14 '20 at 12:19

0 Answers0