Python - when one integer variable changes, make the second variable equal

I have two integers x and ythat are equal to each other. Whenever I change x, I want the change also reflected in y. How can I do this with Python?

I think this can be achieved in some way by specifying both variables in the "memory location" where the value is stored.

+4
source share
5 answers

lists and dictionaries act like pointers in python, so a hacked version of what you are trying might look like this:

In [16]: x = y = [0]

In [17]: x
Out[17]: [0]

In [18]: y
Out[18]: [0]

In [19]: x[0] = 10

In [20]: y
Out[20]: [10]

In [21]: x
Out[21]: [10]
+1
source

, ... / , ,

0

Rosetta Code:

Python , Python () . Python - , "" . ( , Pythonistas name "variable", bind "assign" ).

, , y x - x, , y.

x y :

  • Multiple assignments (bindings)

    >>> x = y = 9
    >>> print (x, y)
    (9, 9)
    >>> x = 6  # won't change y
    >>> print (x, y)
    (6, 9)
    
  • Unpacking packages

    >>> x, y = [9] * 2
    >>> x, y = (9, ) * 2  # alternative
    >>> print (x, y)
    (9, 9)
    >>> x = 6  # y says "nice try, x"
    >>> print (x, y)
    (6, 9)
    
0
source

You can not.

You will need to figure out another way to track things. I think you can probably structure your code to use a mutable data type , like listeither dict, or perhaps create a custom one:

class MutableInt:
    def __init__(self, value=0):
        self._value = value

    def __add__(self, other):
        self._value += other

    def __repr__(self):
        return str(self._value)

mutable_int = MutableInt(4)
print(mutable_int) # 4

def addOne(mutable_int):
    mutable_int += 1

addOne(mutable_int)
print(mutable_int) # 5
0
source

You can change xor yusing the function, try the following code:

def change_x(value):
    global y
    y = value
    return value

def change_y(value):
    global x
    x = value
    return value

x = y = 3
print(x,y)
x = change_x(5)
print(x,y)
y = change_y(6)
print(x,y)
-1
source

All Articles