abcd
abcd

Reputation: 171

Python numpy bug or feature

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

Upvotes: 2

Views: 147

Answers (3)

avasal
avasal

Reputation: 14854

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

Upvotes: 8

lvc
lvc

Reputation: 35059

This isn't a numpy thing, its a standard Python thing. The same will happen with lists:

>>> a = b = []
>>> a.append(5)
>>> a
[5]
>>> b
[5]
>>> a[0] = 10
>>> a
[10]
>>> b
[10]

When you do this:

>>> a = 5

You are rebinding the name 'a' to a different object - but when you do slice assignment, you're modifying part of the existing object in place.

Upvotes: 2

Tim Pietzcker
Tim Pietzcker

Reputation: 336078

This is not numpy's problem, this is a typical Python feature: Everything is an object, but some objects are mutable and some aren't.

So if you do x=y=z=["foo", "bar"], you bind the exact same object to the three variables. This means that if you change x by mutating the list it references, you change the object that y and z are pointing to, too.

Upvotes: 1

Related Questions