Problem with assignment. Python error or mine?

MRAB python at mrabarnett.plus.com
Thu Dec 21 10:37:02 EST 2017


On 2017-12-21 15:05, rafaeltfreire at gmail.com wrote:
> Dear community, I am having the following problem when I am assigning the elements of a vector below a certain number to zero or any other value.
> I am creating a new variable but Python edits the root variable. Why?
> 
> import numpy as np
> 
> X=np.arange(1, 10000, 1) #root variable
> x1=X
> x1[x1<10000]=0
> 
> print(X)
> Out[1]: array([ 0.,  0.,  0., ...,  0.,  0.,  0.])
> 
> Why????????? It is supposed to be the original value
> Thank you for your time
> Rafael
> 
Python never makes a copy unless you ask it to.

What x1=X does is make the name x1 refer to the same object that X 
refers to. No copying.

As you're using numpy, you can use the .copy method:

x1 = X.copy()

This makes the name x1 refer to a new copy of the object that X refers to.



More information about the Python-list mailing list