Why does my variable's value is changed by a line that doens't touch it in Python? -
this question has answer here:
- why original list change? 2 answers
the answer question seems pretty straightforward : can't doesn't. yet believe happening me , driving me crazy. therefore appreciate opinion.
here's situation. i'm writing script has following function in :
def reducereferencecode(): code = referencecode if e == 7: critlimit = 2 elif e == 4: critlimit = 1 if d < critlimit: 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 referencecode variable - passed argument program sys.argv - changed between 2 print commands. main function prints both referencecode , reduced code comparison purposes, value stored in code
here's 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] reference code [1, 4, 3, 4, 7, 7, 2, 0, 6, 1, 9, 2] , reduced reference code [1, 4, 3, 4, 7, 7, 2, 0, 6, 1, 9, 2]
both variables should not have same value , don't see why operation on code[i] affecting referencecode's value.
any insight highly appreciated :-)
the value of referencecode
list. list has reference called code
. updating list either of these references changes one-any-only list object. fix copy list
code = referencecode[:]
Comments
Post a Comment