Python Sigma Sums
Question: I have a list of values x=`[1,-1,-1,1,1,-1,1,-1,1,-1]` and I have another
blank list `y=[ ]`

I am trying to create a function that will take a sigma sum of values in `x`
and store them in `y`.

For instance, `y[0]` should be the sum of `x[0]*x[0] + x[0]*x[1] + x[0]*x[2] +
... + x[0]*x[9]` .

Similarly, `y[1]` should be the sum of `x[1]*x[0] + x[1]*x[1] + x[1]*x[2]+ ...
+ x[1]*x[9]`.

This has to be done for `y[0] through y[9]`.

Also, in the sums, `x[i]*x[i]` must be zero. So for instance in `y[0]`,
`x[0]*x[0]` has to be zero. Similarly, in the sum for `y[1]`, `x[1]*x[1]` must
be zero.

This is my code, but it always gives me some sort of error regarding indices:

    
    
    x=[1,-1,-1,1,1,-1,1,-1,1,-1]
    y=[]
    def list_extender(parameter):
        for i in parameter:
            parameter[i]*parameter[i]==0
            variable=numpy.sum(parameter[i]*parameter[:])
            if variable>0:
                variable=1
            if variable<0:
                variable=-1
            y.append(variable)
        return y
    

Then i run `print list_extender(x)` which should print list `y` with the sigma
sums described above, but I always get an error. What I am doing wrong? The
help will be highly appreciated!


Answer: You're doing way too much typing and computation here. Your function could be
shorter and simpler if you computed the sum of `x` first, then used that to
compute the elements of `y`. It'd also run faster.

Just do this:

    
    
    x_sum = sum(x)
    y = [item * (x_sum - item) for item in x]
    # or, if you really want to store the results into an existing list y
    # y[:] = [item * (x_sum - item) for item in x]
    

Replace `sum` and the list comprehension with numpy operations if you're using
numpy:

    
    
    import numpy as np
    x = np.array([1,-1,-1,1,1,-1,1,-1,1,-1])
    y = x * (x.sum() - x)
    

