Eric Klaus
Eric Klaus

Reputation: 955

Reference identifier in python

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 )

Upvotes: 0

Views: 81

Answers (1)

Alexis
Alexis

Reputation: 337

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.

Upvotes: 2

Related Questions