-1

In the example below, when calling the .add() method on the set B, set A is also affected:

A = {0,1,3,4,5}
B = A 
B.add(10)

I expect this because A and B are both pointing to the same set object.

However, in this slightly different situation, set A is unaffected:

A = {0,1,3,4,5}
B = A
B = B - {0,1}

In this second example, why is a new object created for B to point to? What explains this difference in behaviour?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
nyptop
  • 59
  • 1
  • 2
  • 9
  • 1
    Differently to what? Every mutable object will show the same behaviour, `B = A` **does not** create a copy. The difference is the kinds of operation - `B.add(10)` mutates the object, whereas `B - {0, 1}` creates a new one. – jonrsharpe Oct 14 '20 at 16:04
  • @jonrsharpe: The main question here is about the second case, not the first. Your duplicate only explains the first (which the OP already seems to understand). I wouldn't be surprised if this is a duplicate, but it's not a duplicate of [the question you linked](https://stackoverflow.com/q/4588100/364696). – ShadowRanger Oct 14 '20 at 16:07
  • Then the only real answer is *"because that operation returns a new set, rather than mutating the existing set, [as documented](https://docs.python.org/3/library/stdtypes.html#frozenset.difference)"*. – jonrsharpe Oct 14 '20 at 16:23

2 Answers2

1

You're absolutely correct about the first case - A and B are the same object.

For the second example, the expression B - {0,1} is creating a new set. That new set is being assigned back to B, so now B isn't the same as A anymore.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
1

In your first case, yes, A and B are aliases to the same object, so mutating through one alias is visible on both.

In your second case, B - {0,1} is creating a brand new set object and B = is rebinding the name B to it (any time you see plainname = somethingelse, it doesn't matter what was bound to plainname before; it's now rebound to something new), so it's no longer aliasing the same set as A. You could mutate B in place, causing A to change as well, by doing:

B -= {0,1}

as sets implement a mutating in-place subtract operation which is invoked for -= (but not -).

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271