0

The answer to my question seems pretty straightforward : it can't so it doesn't. Yet I believe it is happening to me and it is driving me fairly crazy. Therefore I would very much appreciate your opinion.

Here's the situation. I'm writing this script which has the following function in it :

    def ReduceReferenceCode():

        Code = ReferenceCode

        if E == 7:
            CritLimit = 2
        elif E == 4:
            CritLimit = 1

        if D < CritLimit:
            for i in [4, 5, 6]:
                if Code[i] >= CritLimit:
                    print ReferenceCode
                    Code[i] = Code[i] - CritLimit
                    print ReferenceCode
                    break
        else:
            Code[7] = Code[7] - CritLimit
        Code[9] = 1

        return Code

The value of my ReferenceCode variable - which is passed as an argument to the program with sys.argv - is changed between the two print commands. My main function prints both ReferenceCode and my reduced code for comparison purposes, which is the value stored in Code

Here's the program's output:

    [1, 4, 3, 4, 9, 7, 2, 0, 6, 7, 9, 2]
    [1, 4, 3, 4, 7, 7, 2, 0, 6, 7, 9, 2]
    The reference code is [1, 4, 3, 4, 7, 7, 2, 0, 6, 1, 9, 2] and the reduced reference code is [1, 4, 3, 4, 7, 7, 2, 0, 6, 1, 9, 2]

Both variables should not have the same value and I really don't see why the operation on Code[i] is affecting ReferenceCode's value.

Any insight would be highly appreciated :-)

MrSquid
  • 3
  • 1

2 Answers2

0

You did that :

Code = ReferenceCode

So both references are pointing to the same object.

Khaled
  • 411
  • 3
  • 10
0

The value of your ReferenceCode is a list. That list has another reference called Code. Updating the list from either of these references changes the one-any-only list object. The fix is to copy the list

Code = ReferenceCode[:]
tdelaney
  • 73,364
  • 6
  • 83
  • 116
  • I see, so I guess it works like pointers in C/C++. I assumed python was simply and automatically going to copy each value of the ReferenceCode list to a new list called Code. – MrSquid Nov 13 '16 at 00:31