How to create a list of variable references in Python?

Viewed 619

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?

1 Answers

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
Related