0

I have this code (it has been reduced for simplicity, so don't pay attention to content):

for x in range(1,4):
    print(x)
    print(vLast)

    #1st level
    for the_key,the_value in graph.items():
        numerator=0
        denominator=0
        result=0

        #2nd level
        for the_key2,the_value2 in graph[the_key].items():
            numerator = 0
            denominator = 5
            numerator = the_value2

            result = numerator/denominator

        result = alpha*result+(1-alpha)/len(vLast)
        print(vLast['p2p']) #Line A
        vCurrent[the_key] = result #Line B
        print(vLast['p2p'])
    vLast=vCurrent #Line C
    x=x+1

When x = 2, after executing Line B, vLast['p2p'] takes the value of a result variable.

I understand that it has to do with reference identifiers, but I don't want to change value, before Line C is executed, otherwise 1st level 'for' loop uses different values of vLast['p2p'] before exiting

In other words, how not to change the values of vLast until Line C is executed?

Here is the output of above prints at x = 2

    2
    {'p2p': 0.17517241379310347, 'nnn': 0.3451724137931035, 'ppp': 0.3451724137931035, 'fff': 0.3451724137931035}
    0.17517241379310347 
    0.20750000000000002 
...

(I expect last line to stay 0.17517241379310347 instead of 0.20750000000000002 )

3
  • Please read and follow the posting guidelines in the help documentation, as suggested when you created this account. Minimal, complete, verifiable example applies here. We cannot effectively help you until you post your MCVE code and accurately describe the problem. We should be able to paste your posted code into a text file and reproduce the problem you described. Commented Nov 9, 2018 at 1:19
  • 1
    @Prune , this is general knowledge question regarding reference identifiers, and it must be pretty clear from explanations above. And as you can see Answer to this post is pretty simple, but very helpful. Regards Commented Nov 9, 2018 at 1:23
  • 1
    Good enough; you got your solution. Do note that this issue has been handled many times on SO, and that your code is not minimal to show the problem. Yes, the answer is simple -- which suggests that simple code should demonstrate the problem. Commented Nov 9, 2018 at 1:28

1 Answer 1

2

You need to use shallow copies

vLast = vCurrent.copy() #Line C

This will copy the content of vCurrent into vLast, but the two objects will not be bound as they are know. The same method is available for lists.

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.