Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python numpy bug or feature

Tags:

python

numpy

Is this a bug or a feature?

import numpy as np
a=b=c=0
print 'a=',a
print 'b=',b
print 'c=',c

a = 5
print 'a=',a
print 'b=',b
print 'c=',c

b = 3
print 'a=',a
print 'b=',b
print 'c=',c

x=y=z=np.zeros(5)
print 'x=',x
print 'y=',y
print 'z=',z

x[2]= 10
print 'x=',x
print 'y=',y
print 'z=',z

y[3]= 20
print 'x=',x
print 'y=',y
print 'z=',z

The output of the code shows me that the numpy initializations are clones of each other while python tends to treat them as independent variable.

a= 0
b= 0
c= 0
a= 5
b= 0
c= 0
a= 5
b= 3
c= 0
x= [ 0.  0.  0.  0.  0.]
y= [ 0.  0.  0.  0.  0.]
z= [ 0.  0.  0.  0.  0.]
x= [  0.   0.  10.   0.   0.]
y= [  0.   0.  10.   0.   0.]
z= [  0.   0.  10.   0.   0.]
x= [  0.   0.  10.  20.   0.]
y= [  0.   0.  10.  20.   0.]
z= [  0.   0.  10.  20.   0.]

I hope the problem is clear. Is this a bug or a feature in numpy?

Regards

like image 262
abcd Avatar asked Jul 05 '26 00:07

abcd


1 Answers

this is not a bug,, and it is not about numpy initialization, this is a python thing,, check id of both x,y & z in your case, they point to same element

What your code is doing is multiple initialization in the same line, when this happens, only 1 object is created and all the variables refer to the same.

See the below example, how rebinding helps...

In [19]: a=b=[1,2,3]

In [20]: a
Out[20]: [1, 2, 3]

In [21]: b
Out[21]: [1, 2, 3]

In [22]: a[1]
Out[22]: 2

In [23]: a[1] = 99

In [24]: a
Out[24]: [1, 99, 3]

In [25]: b
Out[25]: [1, 99, 3]

In [26]: id(a)
Out[26]: 27945880

In [27]: id(b)
Out[27]: 27945880

In [28]: a = a[:]   # This is Rebinding 

In [29]: a
Out[29]: [1, 99, 3]

In [30]: id(a)
Out[30]: 27895568  # The id of the variable is changed
like image 180
avasal Avatar answered Jul 06 '26 14:07

avasal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!