1

I have isolated the following part of a bigger code:

import numpy as np

population= np.random.normal(0,1,5)
individuals=population

print(population)

for i in range(len(individuals)):
    individuals[i]=0

print(population)

response:

[-0.1791731  -0.0756427   0.44463943 -0.51173395  0.9121922 ]
[0. 0. 0. 0. 0.]

I can't understand why the results are not identical.

12
  • I get an error: name 'pop' is not defined. Do you mean print(population)? Commented May 14, 2018 at 1:03
  • what is the variable pop? Commented May 14, 2018 at 1:04
  • Also, the reason you get this output is because you point individuals as a reference to population, so you are changing population when you change individuals Commented May 14, 2018 at 1:04
  • Sorry changed the pop, that was a mistake Commented May 14, 2018 at 1:05
  • you change each item to 0 in the for loop... what is it you are trying to achieve with the for loop? Commented May 14, 2018 at 1:06

1 Answer 1

1

use .copy() if you want to copy the content of the numpy array, what you are doing at the moment, is copying a pointer to the list. So both variables point to the same data, so if one changes they both change.

import numpy as np

population= np.random.normal(0,1,5)
individuals=population.copy()

print(population)

for i in range(len(individuals)):
    individuals[i]=0

print(population)

For non-numpy lists you can use [:] eg

a = [1,2,3]
b = a[:]
Sign up to request clarification or add additional context in comments.

2 Comments

Oh I see, I just tested with [:] and as you told, it didn't work with numpy list. I am currently trying with .copy(), it works on the sample I gave here, but I am currently implementing it on my main code. I will come back to you if I have more problems. Thank you very much !
Use population.copy() not [:] as mentioned in the answer that is for non-numpy lists

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.