Skip to content
Advertisement

In Python, why my variable StartingU get updated when I only update the variable AverageU in my for loops? What is wrong with the code?

The purpose is to calculate the average value (AverageU) from a starting array (StartingU)

JavaScript

The for loops that calculate the average values for AverageU

JavaScript

Output:

JavaScript

The problem is why StartingU gets updated? It should be unchanged

JavaScript

Advertisement

Answer

AverageU changed since this code, not after for loop.

JavaScript

AverageU and StartingU are the same instances. You can check it with is function.

JavaScript

You should make a new instance as the comment said.

JavaScript

AverageU = StartingU This code just makes another reference to the same object with a new name and this indicates the same memory. You can check the memory address of the variable with function id

You can compare like this.

JavaScript

Notice

Copy with the colon is actually a shallow copy, it copies only the reference of the nested list.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement