3

I am using Python 3. Suppose I have 2 variables and create a list containing the 2 variables

a = 48
b = 42
arr = [a, b]

If I modify a then arr remains the same, this is because a is an integer, if it was an object, then the object in arr (that is technically a reference to the same object) gets updated. I want arr[0] to be a reference to the variable a rather than the value itself, so that if a is changed then arr[0] is changed as well. How do I do that?

  • You're trying to understand mutability. See this answer https://stackoverflow.com/questions/9172263/a-mutable-type-inside-an-immutable-container. – vanPelt2 May 22 '20 at 15:46
  • "a reference to the variable ``a``" There is no such thing in Python. Can you clarify what *behaviour* you want? Are ``a`` and ``b`` function locals or globals? Do you always need a list of "variable references", or also independent references? Do you need ``a`` and ``arr`` to appear "normal", or is a wrapping helper object acceptable? – MisterMiyagi May 22 '20 at 16:06
  • `a` and `b` are globals, and I want them to appear normal @MisterMiyagi – ѕняєє ѕιиgнι May 22 '20 at 16:21

1 Answers1

1

Unfortunately, it is not possible. Since integer is immutable type, whenever you change integer value, you essentially create new object.

You can check this:

>>> a = 48
>>> b = 42
>>> arr = [a, b]
>>> id(a)
263256736
>>> id(arr[0])
263256736
>>> a = 11
>>> id(a)
263256144 # it is a new object already
>>> id(arr[0])
263256736 # still points to the old object
Alexander Pushkarev
  • 1,075
  • 6
  • 19