2 lists manipulated for a 3rd list


If I have a list of directions:

LIST_A=['N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW']

plus a list of random directions:


How do I arrive a list that looks at the directions in LIST_B and returns the opposite direction – plus one increment in the clockwise direction.

For example, the code would look at the first element in LIST_B (‘E’) – return the opposite direction (‘W’) plus one increment in the clockwise direction – which would be ‘WNW’.



Asked By: GDog



You can use modulo arithmetic:

out = []
for v in LIST_B:
    idx = LIST_A.index(v)
    out.append(LIST_A[(idx + 8 + 1) % len(LIST_A)]) # 8 for opposite, 1 for increment to clockwise direction



['WNW', 'SW', 'NNE', 'N', 'ENE', 'SSW']
Answered By: Andrej Kesely

It is easiest if you first convert the direction to an index and then perform the operations on it. So it’s something like this:

LIST_A=['N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW']

# iterate over all directions in LIST_B
for direction in LIST_B:
  # get index of element in LIST_A
  index = LIST_A.index(direction)
  # turn by 180 degrees
  index += len(LIST_A)//2
  # add one increment in clockwise direction
  index += 1
  # modulo for directions with over 360 degrees
  index %= len(LIST_A)
  # output result
Answered By: grottenolm