Simple loop for making sure angle is less than 360 [Python]

Question:

I know this is a simple problem, but I cannot get this to work. I have a list of angles, and I need them to be less than 360 degrees. How can I write a loop that will be if the angle is more than 360, to subtract 360? I tried:

for i in theta_degrees:
    while i>360:
        i -= 360

But that didn’t work for some reason.

Asked By: GlassSeaHorse

||

Answers:

To replace the values in-place, you need to replace the values … in-place, not copy them to another variable:

for i in range(len(theta_degrees)):
    while theta_degrees[i] > 360:
        theta_degrees[i] -= 360

or you can use a shorter & faster & more functional approach with a list comprehension and modulo operator:

theta_degrees = [i % 360 for i in theta_degrees]

or if theta_degrees is a generator (or a very long list), you can achieve lazy evaluation using a generator expression:

theta_degrees = (i % 360 for i in theta_degrees)
Answered By: Aprillion

You can do this more easily with a list comprehension, and with the modulo operator instead of a while loop.

theta_degrees = [ i%360 for i in theta_degrees ]
Answered By: khelwood

If you are using Numpy arrays, this should also work:

a[a >= 360] -=360
Answered By: A K
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.