In python everything works by reference:
>>> a = 1
>>> d = {'a':a}
>>> d['a']
1
>>> a = 2
>>> d['a']
1
I want something like this
>>> a = 1
>>> d = {'a':magical pointer to a}
>>> d['a']
1
>>> a = 2
>>> d['a']
2
What would you substitute for magical pointer to a so that python would output what I want.
I would appreciate general solutions (not just for the above dictionary example with independent variables, but something that would work for other collections and class/instance variables)
Pointers tend to create complexity in the code, where Python mainly focuses on usability rather than speed. As a result, Python doesn't support pointer. However, Python gives some benefits of using the pointer. Before understanding the pointer in Python, we need to have the basic idea of the following points.
You can only reference objects in Python. Lists, tuples, dictionaries, and all other data structures contain pointers.
Python lists don't store values themselves. They store pointers to values stored elsewhere in memory. This allows lists to be mutable.
Uses of the Pointer in PythonWith Pointers, dynamic memory allocation is possible. Pointers can be declared as variables holding the memory address of another variable.
What about a mutable data structure?
>>> a = mutable_structure(1)
>>> d = {'a':a}
>>> d['a']
1
>>> a.setValue(2)
>>> d['a']
2
An implementation might look like
class mutable_structure:
def __init__(self, val):
self.val = val
def __repr__(self):
return self.val
The standard solution is to just use a list; it's the easiest mutable structure.
a = [1]
d = {'a': a}
a[0] = 2
print d['a'][0]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With