-3

I have the following code:

a=(0,1)
x={a}

I changed a as

a=(1,2)

but x remains the same as before. I am wondering how I can change x whenever I change a?

luw
  • 207
  • 3
  • 14
  • 1
    I don't think this is possible. A set requires a hashable object, and all of the mutable types are not hashable. To do what you want, you'd need to use a mutable object. See https://stackoverflow.com/a/31340810/5666087 – jkr Aug 23 '20 at 23:43
  • 1
    You did not change the object which was previously in `a` and which is still in `x`. You just assigned a different object to variabe `a` (without modifying `x`). Also, there is no way to modify the original object, because it is a tuple and tuples are immutable. – zvone Aug 24 '20 at 00:09
  • When you say that you "changed a" you are a bit confused about how variable naming works in Python. You did not change `a`. Rather, you attached the `a` label or tag to an entirely different object. Meanwhile, the thing inside the set remains the original object -- an object that also happens to be immutable, but that's a somewhat different topic. This might help: [Facts and myths about Python names and values](https://nedbatchelder.com/text/names.html). – FMc Aug 24 '20 at 00:09

2 Answers2

1

You can create an object to hold your data. The object implements __hash__, so it can be used in a set.

class Container:
    def __init__(self, data=None):
        self.data = data or []
        
    def __repr__(self):
        return str(self.data)

x = {a}
print(x)  # {[]}

a.data = [0, 1, 2]
print(x)  # {[0, 1, 2]}

See https://stackoverflow.com/a/31340810/5666087 for more information.

jkr
  • 17,119
  • 2
  • 42
  • 68
0

Switch over to a list and you could do. Otherwise it's not possible with your variables.

a=[0,1]
x=[a]
print(a)
print(x)
a[0]=1
a[1]=2
print(a)
print(x)
Arundeep Chohan
  • 9,779
  • 5
  • 15
  • 32