[SciPy-user] Avoiding For Loops Question

David Warde-Farley dwf@cs.toronto....
Fri Jun 5 13:53:01 CDT 2009

On 5-Jun-09, at 1:48 PM, Whitcomb, Mr. Tim wrote:

> You can indeed - I checked and made sure.  What is the generally
> accepted practice for their inclusion?  Sometimes in my Fortran code I
> use (:) to make it clear that these are array operations, but is the
> Numpy/Scipy convention to leave them out if they are not necessary?

As Josef hinted at but (as far as I can see) never explicitly spelled  
out, [:] on the left hand side indicates e.g. that for foo[:] = bar  
the contents of bar should be copied into the location already pointed  
to by foo. foo = bar is basically a reference assignment.

In [1]: x = zeros(50)

In [2]: y = arange(50)

In [3]: x[:] = y

In [4]: x[0] = -500 # won't affect y, since previous line was copy

In [5]: y[0]
Out[5]: 0

In [6]: x = y

In [7]: x[0] = -500

In [8]: y[0]
Out[8]: -500

In [9]: x[:] = arange(100)
ValueError                                Traceback (most recent call  

/Users/dwf/<ipython console> in <module>()

ValueError: shape mismatch: objects cannot be broadcast to a single  

In [10]: x = arange(100) # succeeds

In [11]: len(x)
Out[11]: 100

More information about the SciPy-user mailing list