Reputation: 113
I am doing a form of breadth first search in a directed graph, and I want to store data recursively in the form (node, parent data*)
. How is this recursive? Starting with the root it will look like (root, None)
. Then the data for its child will be (child1, (root, None))
. The child of child1 will then store (child2, (child1, (root, None)))
.
Obviously as the path length grows this becomes a lot of data. My question is: Lets say I assign a variable to the parent data, say parent_data = (root, None)
and then write the child data as (child1, parent_data)
, is the variable storing all the parent data or is it simply a reference that will access the parent data upon request? I don't want to be storing all of this information multiple times.
What I wish I could do was simply have a C++ style pointer where in C++ notation I would assign tuple * parent_pointer = &(root, None)
.
Is this possible in Python or even necessary?
Apologies if the question is not clear, I am new to CS.
Upvotes: 0
Views: 44
Reputation: 3337
If you're using lists
, or tuples
, or dict
, or even any custom created class - to store the parent_data, it will use the pointer by default. i.e. it won't copy the data.
Example:
In []: parent_data = ['root', None]
In []: child_data = ['child1', parent_data]
In []: child_data
Out[]: ['child1', ['root', None]]
In []: child_data[1][1] = "THIS USED TO BE NONE"
In []: child_data
Out[]: ['child1', ['root', 'THIS USED TO BE NONE']]
In []: parent_data
Out[]: ['root', 'THIS USED TO BE NONE']
In []: id(parent_data)
Out[]: 4705828232
In []: id(child_data[1])
Out[]: 4705828232
To do a value based copy, you need to use: parent_data.copy()
Upvotes: 2
Reputation: 3582
Python variables are references to objects, this code
obj1 = obj2
will store a reference to obj2 in obj1 - you can check it with the help of id function.
The whole idea of Python "by reference" approach is to make issue of memory management mute
Upvotes: 1