# [SciPy-user] Avoiding For Loops Question

Joseph Smidt josephsmidt@gmail....
Fri Jun 5 12:47:14 CDT 2009

```All right guys, last one:

for l in xrange(1,1000):
for m in xrange(0,l+1):
Alm[l][m] = alm[l][m]*cl[l]
Blm[l][m] =alm[l][m]*cl[l]

Here is one where the second index depends on value of the first.

Joseph Smidt

On Fri, Jun 5, 2009 at 10:26 AM, <josef.pktd@gmail.com> wrote:
> On Fri, Jun 5, 2009 at 12:37 PM, Whitcomb, Mr. Tim
> <tim.whitcomb@nrlmry.navy.mil> wrote:
>>>    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.
>
> these 2 are two different operations
>
>  a[:,:] = x[:, numpy.newaxis] + y[:,:]
>
> on right side:  y[:,:] is the same as y, [:,:] is redundant
> on the left side a[:,:] =    assigns the content of the right side to
> existing array `a`
>      if the dimensions don't agree, then you get an exception
>
> a = x[:,numpy.newaxis] + y
> this assigns the temporary result of the right side to the name `a`,
> no matter what `a` was before
>
> so, in the examples above, I think, you can drop all [:], [:,:]
>
> Josef
>
>
>>
>> Tim
> _______________________________________________
> SciPy-user mailing list
> SciPy-user@scipy.org
> http://mail.scipy.org/mailman/listinfo/scipy-user
>

--
------------------------------------------------------------------------
Joseph Smidt <josephsmidt@gmail.com>

Physics and Astronomy
4129 Frederick Reines Hall
Irvine, CA 92697-4575
Office: 949-824-3269
```