-1

The variable 'operations' which is a list is changing after the for loop is run despite their being no line that explicitly says for its value to change. Here is my code:

validOperations = ['(', ')', '^', '*', '/', '+', '-']
operations = ['+', '*', '/']
newOp = operations  

for y in range(len(newOp) - 1):
        for z in range(len(newOp) - 1):
                if(validOperations.index(newOp[z]) > validOperations.index(newOp[z+1])):
                        oldVal = newOp[z]
                        newOp[z] = newOp[z+1]
                        newOp[z+1] = newOp[z]
                        print(newOp)
                        print(operations)

What can I do to make it to where the value of operations stays constant?

1 Answers1

2

newOP is not a copy of operatoions. newOp is an alias for operations. Which means that when newOP changes, operations changes as well. You need to tell Python explicitly to copy your list:

newOp = operations[:]

If your list is more than one level deep in nesting however, using slice notation will fail. You must use copy.deepcopy instead.

Community
  • 1
  • 1
Christian Dean
  • 22,138
  • 7
  • 54
  • 87