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?

3
  • You're trying to understand mutability. See this answer stackoverflow.com/questions/9172263/…. Commented May 22, 2020 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? Commented May 22, 2020 at 16:06
  • a and b are globals, and I want them to appear normal @MisterMiyagi Commented May 22, 2020 at 16:21

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.