1

I have a code as below:

v={'B', 'C', 'a', 'f', 'g', 'c', 'd'}
u=v
t={'B', 'C','H'}
u|=t
print v,u

It gives this result:

set(['a', 'C', 'B', 'd', 'g', 'f', 'H', 'c']) set(['a', 'C', 'B', 'd', 'g', 'f', 'H', 'c'])

Why on Earth would line 4 change v?? I only expect u to change. I would understand if I would write v=u, but not other way.

  • 1
    Take a look at [Python's Passing by References](https://stackoverflow.com/a/42908412/674039). After `u = v`, the u and v are just "nametags" attached to the same identical object. Any changes to that object will be reflected on all references to it. – wim Nov 19 '19 at 06:39
  • `u=v` are referring the same object so use `u=v[:]` or `u=v.copy()` – U13-Forward Nov 19 '19 at 06:42
  • 2
    From Python Doc. > Assignment statements in Python do not copy objects, they create bindings between a target and an object. So u = v just means the variable u refers to the same object as v. Thus, whenever you change u, you change v too. – HelloWorld Nov 19 '19 at 06:44
  • You can use frozensets if you don't need the mutability. They're also hashable, so you can have sets of sets. – gilch Nov 19 '19 at 06:44

0 Answers0