0

I used to think that python used to work with references or respectively with copies of references when values are passed as function arguments.

Now I tried the following example and do not understand anything anymore even after reading a bit up on the topic.

import numpy as np
import networkx as nx

graph = nx.DiGraph()
test = np.array([1, 1, 1], dtype=np.bool)
graph.add_edge(1, 2, data=True)
print graph[1][2]['data'] # shows True as expected
graph[1][2]['data'] = test[0]
print graph[1][2]['data'] # shows True as expected. Still fine

test[0] = False
print graph[1][2]['data'] # shows True instead of False

Shouldn't it then print False? I thought that assignement would make the graph[1][2]['data'] point to test[0]. However it seems that it actually uses references to True and False and I seem to don't really understand pythonic assignment.

Is there a way how to make it point to the specific entry of the array or is this impossible in python? And not to the content of the array entry?

1 Answer 1

1

when you did graph[1][2]['data'] = test[0] you took the current value of test[0] and put it in the graph. when you did test[0] = False you changed the value of test[0] to point to a diffrent value, but the graph point to the old value.

a simplified example of your case can be:

x = 1
y = x
x = 2
print y # will print 1

Since you changed x's its value, but y referenced the old value. in python when you assign (use =) you take the value of the right side and place it on the left side, but in your case when you did test[0] = False you didnt change the value, you overriden it with a diffrent value.

if you want to change something and have it shared, you need to manipulate the same instance, for example:

class A(object):
    def __init__(self):
        self.x = 1
y = A()
lst = []
lst.append(y)
y.x += 1
print lst[0].x # will print 2

here the instance of A was shared so the value change was visible by accessing it with the list

Sign up to request clarification or add additional context in comments.

Comments

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.