Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python equivalent of pointers

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)

like image 205
random guy Avatar asked Jan 14 '10 15:01

random guy


People also ask

Why pointers are not there in Python?

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.

Do Python lists use pointers?

You can only reference objects in Python. Lists, tuples, dictionaries, and all other data structures contain pointers.

Do Python lists store values or pointers?

Python lists don't store values themselves. They store pointers to values stored elsewhere in memory. This allows lists to be mutable.

Does Python have pointers and dynamic memory pointers?

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.


2 Answers

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
like image 147
danben Avatar answered Oct 23 '22 17:10

danben


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]
like image 35
Johann Hibschman Avatar answered Oct 23 '22 17:10

Johann Hibschman