# [SciPy-user] Avoiding For Loops Question

Ivo Maljevic ivo.maljevic@gmail....
Fri Jun 5 12:56:45 CDT 2009

```Tim,
Just out of curiosity, why:

> i = numpy.arange(len(x))
> a[:] = i[:]*(i[:]+1)/2*x[:]

and not:

> i = numpy.arange(len(x))
> a = i*(i+1)/2*x

Ivo

2009/6/5 Whitcomb, Mr. Tim <tim.whitcomb@nrlmry.navy.mil>:
>>    Now, is it possible to write get around these types of for
>> loops using any tools from scipy?
>
> Numpy, yes.
>
>> for i in xrange(len(x)):
>>      a[i] = i*(i+1)/2*x[i]
>>
>
> The values of i are just indices, and those can be precomputed
> beforehand:
> i = numpy.arange(len(x))
> a[:] = i[:]*(i[:]+1)/2*x[:]
>
>> for i in xrange(y.shape[0]):
>>     for k in xrange(y.shape[1]):
>>         a[i] += x[i] + y[i][k]
>
> Break the sum into two pieces - the x component is just repeated
> y.shape[1] times, and y is added up along the second axis:
> a[:] = x[:]*y.shape[1] + y[:].sum(axis=1)
>
>> for i in xrange(y.shape[0]):
>>     for k in xrange(y.shape[1]):
>>         a[i][k] = x[i] + y[i][k]
>
> Here, you are copying y into a, then adding the same value of x across
> an entire axis.  Use array broadcasting to make x be the same shape as
> y, but with each column the same value:
> a[:,:] = x[:, numpy.newaxis] + y[:,:]
>
> I don't know what the style standard is regarding using the colons to
> indicate entire arrays (i.e.
> a = x[:,numpy.newaxis] + y instead), but these should work for you.
>
> Tim
>
>
> _______________________________________________
> SciPy-user mailing list
> SciPy-user@scipy.org
> http://mail.scipy.org/mailman/listinfo/scipy-user
>
```