Imagine I have:
x = 2
y = x
y = 3
Output:
x = 2
y = 3
What I want:
x = 3
Right now, as I have it, this doesn't set x to 3, but y to 3. How can I change this so y acts as a pointer to x. I want to edit x, not y. Previously, I believe I saw a page about using mutable variables. I don't think I completely understand how variables work in Python.
CodePudding user response:
You could use a list
:
x = [2]
y = x
y[0] = 3
print(x)
Output:
[3]
CodePudding user response:
It is because int type is immutable in python, and the refference from y variable to x is not created when you try to do that. You can easily check it just by printing id(x) and id(y).
If you don't want to use a list, as Erik McKelvey recomended to you, you can try this https://pypi.org/project/mutableint/