Search code examples
pythonvariables

How do I Set Variable Dependent on Another Variable to Update when the Original Variable Updates?


In python, let's run the following lines of code:

x = 0
y = x
x += 1
print(y)
print(x)

The first line of output is clearly different from the second, even though we set x=y in line 2. Anyone experienced with programming as a whole would know that.

However, is there a way to make x update as y does?


Solution

  • To expand on @juanpa's comment, you can get this behavior if you wrap the value in a list:

    x = [0]
    y = x
    x[0] += 1
    print(y[0])
    print(x[0])