Steven
Steven

Reputation: 321

"resetting" variable in for loop python

I want to substract a number from an array in python but I want to keep the original array.

Here's my code:

for X0 in [X0 * 0.01 for X0 in range(-2,2)]:
    for Y0 in [Y0 * 0.01 for Y0 in range(6,10)]:
        RAm = RA
        Decm = Dec
        RAm[:] = [x - X0 for x in RAm]
        Decm[:] = [x - Y0 for x in Decm]
        RAs = np.sum(RAm)
        Decs = np.sum(Decm)
        #a = np.sqrt(((RAs**2*Decs**2)**2 - RAs**4*Decs**4)/(RAs**2*Decs**2*Decs**2 -Decs**2*RAs**4))
        #b = np.sqrt(((RAs**2*Decs**2)**2 - RAs**4*Decs**4)/(RAs**2*Decs**2*RAs**2 - RAs**2*Decs**4))
        print RA
        print RAm

This gives me that RA is changing even though it should stay the same because I want to substract a different number from RA each loop. How can I fix this?

Upvotes: 0

Views: 1531

Answers (3)

Thijs van Dien
Thijs van Dien

Reputation: 6616

If you're using NumPy anyway, you can leverage the fact that it supports operations on all elements at once.

RAm = np.array(RA) - X0
Decm = np.array(Dec) - Y0

Or even skip those assignments, if you're not using the result for anything but the sum:

RAs = np.sum(np.array(RA) - X0)
Decs = np.sum(np.array(Dec) - Y0)

It is my impression that you are a (Python) beginner, so perhaps stick with basic Python till you feel comfortable with that. All of it can of course be done without NumPy as well:

RAs = sum(x - X0 for x in RA)
Decs = sum(y - Y0 for y in Dec)

However, if you do want to use NumPy, use it properly. That means: use matrix calculations instead of looping. For example, you could do something like this* to obtain an array with the sums for the different Y0 values:

Y0_values = np.array([Y0 * 0.01 for Y0 in range(6,10)])
y_matrix = np.tile(RA, [len(Y0_values), 1])
Y0_matrix = np.tile(Y0_values[np.newaxis].T, [1, len(RA)])
sums = np.sum(y_matrix - Y0_matrix, axis=1)

*Demonstration purposes only. I am far from a NumPy expert, so there might be an even better way to do this. For the very same reason I will not explain how it works; I'm just encouraging you to learn more about NumPy, to your benefit.

Upvotes: 2

Maxim Razin
Maxim Razin

Reputation: 9466

RAm = RA makes RAm an alias of RA; RAm[:] = ... modifies the list in place.

Instead, do just

RAm = [x - X0 for x in RA]

Upvotes: 1

vlad-ardelean
vlad-ardelean

Reputation: 7622

instead of itterating through a list, and making changes to it, do this:

for element in list(your_list_here):
    if element.something():
        your_list_here.remove(element)

Also.. assigning Ram=Ra means every method invocation on the objects, actually refers to the same object. Use Ram = list(Ra) if you want to be safe.

Upvotes: 1

Related Questions