0

I am new to python and programming. Sadly, I got a problem working on a easy task very soon and could not find a answer to this. In the following, I make up a short example:

a0=np.ones(10);
a1=a0;
a2=a0;
sum1=3;
sum2=2;
a1[0]=sum1;
a2[0]=sum2;
print(a1)

However, the first element of the array a1 is 2 instead of 3. Would someone like to explain to me why and additionally show me a proper way to fulfill this? In the real task, I will run loops for different time periods. Within each loop, I generate different values such as mean, median, and sum. (like sum1 and sum2 in the short sample) These values are given to the arrays (like a1 and a2) with a length already defined. By the way, I use JupyterLab to run python 3.

ntopython
  • 3
  • 1
  • 1
    Why are you using semicolons at the end of each line? Python does not require semicolons. – nerdguy Jan 19 '20 at 16:51
  • In addition to the issue of semicolons, why is there no whitespace in your code? _In the following, I make up a short example_ It might also be worth sharing your entire program, alongside the example. – AMC Jan 19 '20 at 18:06
  • I think this is a duplicate of https://stackoverflow.com/q/19951816/11301900, which itself is marked as a duplicate of https://stackoverflow.com/q/2612802/11301900. – AMC Jan 19 '20 at 18:08
  • @nerdguy I do not add semicolons in my codes when I program, but I am not sure whether it is a correct way to do so. Before I posted the question, I found some other posted questions with sample codes ending with semicolons, which I thought might be better, so I just followed. Thank you for your comment, and now I know what is standard. – ntopython Jan 19 '20 at 19:07
  • @AMC You are right that the question is duplicated. It is also regarding reference which I don't know before. Thank you for the reference and I solve the problem by copying the array. – ntopython Jan 19 '20 at 19:19
  • Does this answer your question? [How to clone or copy a list?](https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list) – B. Go Jan 19 '20 at 20:29

1 Answers1

0

If you assign a1=a0, it means that array a1 refers to the referent of a0. In other words, you bind a0 to the same value as a1.

You will see the change in all variables pointing to the same list.

To avoid this, you should copy the array a0, so they do not refer each other:

a0=np.ones(10)
a1=a0.copy()
a2=a0.copy()
sum1=3
sum2=2
a1[0]=sum1
a2[0]=sum2
print(a0)
print(a1)
print(a2)

Outputs as:

a0 : array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])
a1 : array([3., 1., 1., 1., 1., 1., 1., 1., 1., 1.])
a2 : array([2., 1., 1., 1., 1., 1., 1., 1., 1., 1.])
isydmr
  • 649
  • 7
  • 16