0

I am trying to have different ways to access the same variable. I have a bunch of objects that I store in a dict so I can iterate over them. But on occcasion I would like to access them directly (without going through the structure in the dict...)

object1 = someObjectContructor()
someDict = {}

someDict[1] = object1

Can I have the two point to the same object in memory? So that if I change something in object1 that change would be there in the the dictionary?

4
  • The code provided will work (assuming object1 is mutable). Two references to the object will be created, one in someDict, one in object1. Modifying one will modify the other. However, assigning a new value to either will break the link. Commented Mar 23, 2021 at 8:14
  • The important word is mutable. Had object1 been a string, for instance, the answer would have been different, as strings are immutable in Python. You can verify that two objects are identical with the id function (and also the is statement). Commented Mar 23, 2021 at 8:22
  • 1
    Here is a really good article by Ned Batchelder (the guy that brought us Coverage) on when python refers to the same objects and when not. Hope this helps! Commented Mar 23, 2021 at 8:25
  • so assuming object1 has a method that would change a parameter that would work, but having something like object1 = somethingnew will break the link. right? Commented Mar 23, 2021 at 8:26

2 Answers 2

1

Here is a minimal demo showing that it works:

>>> object1 = []
>>> someDict = {}
>>> someDict[1] = object1
>>> someDict[1].append('foo')
>>> object1.append('bar')
>>> print(object1 is someDict[1])
True
>>> print(object1)
['foo', 'bar']
>>> print(someDict[1])
['foo', 'bar']

Of course if you use an assignment you will point to a different object:

>>> object1 = ['baz']
>>> print(object1 is someDict[1])
False
>>> print(object1)
['baz']
>>> print(someDict[1])
['foo', 'bar']
Sign up to request clarification or add additional context in comments.

Comments

0

I did this in the python command line:

object1 = 5
someDict = {}
someDict[1] = object1

print(someDict[1])
# output: 5

object1 = 6
print(someDict[1])
# output: 5

If you change object1 after someDict[1] has been assigned it, someDict doesn't change.

1 Comment

Strings are non mutable. And anyway object1 = 'bar' never tries to change any object but just make the variable point to a different object.

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.