bertibott
bertibott

Reputation: 33

Multiple references to the same variable in Python

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?

Upvotes: 0

Views: 860

Answers (2)

Serge Ballesta
Serge Ballesta

Reputation: 148890

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']

Upvotes: 1

half of a glazier
half of a glazier

Reputation: 2076

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.

Upvotes: 0

Related Questions