Q:

Python: How do I sort array X but carry the same relative sort over to Y?

For example
X=[5,6,2,3,1]
Y=[7,2,3,4,6]

I sort X:
X=[1,2,3,5,6]

But I want the same relative sort applied to Y so the numbers stay in the same positions relative to each other as before:
Y=[6,3,4,7,2]

I hope this makes sense!

A:

Usually, you do a zip-sort-unzip for this
>>> X = [5,6,2,3,1]
>>> Y = [7,2,3,4,6]

Now sort them together:
>>> sorted(zip(X,Y))
[(1, 6), (2, 3), (3, 4), (5, 7), (6, 2)]

Pair that with a "unzip" (zip(*...))
>>> zip(*sorted(zip(X,Y)))
[(1, 2, 3, 5, 6), (6, 3, 4, 7, 2)]

which you could unpack:
>>> X,Y = zip(*sorted(zip(X,Y)))
>>> X
(1, 2, 3, 5, 6)
>>> Y
(6, 3, 4, 7, 2)

Now you have tuple instead of list objects, but if you really need to, you can convert it back.

As pointed out in the comments, this does introduce a very slight dependence on the second list in the sort:  Consider the lists:
X = [1,1,5,7] #sorted already
Y = [2,1,4,6] #Not already sorted.

With my "recipe" above, at the end of the day, you'll get:
X = (1,1,5,7)
Y = (1,2,4,6) 

which might be unexpected.  To fix that, you could pass a key argument to sorted:
from operator import itemgetter
X,Y = zip(*sorted(zip(X,Y),key=itemgetter(0)))

Demo:
>>> X
[1, 1, 5, 7]
>>> Y
[2, 1, 4, 6]
>>> XX,YY = zip(*sorted(zip(X,Y)))
>>> XX
(1, 1, 5, 7)
>>> YY
(1, 2, 4, 6)
>>> from operator import itemgetter
>>> XX,YY = zip(*sorted(zip(X,Y),key=itemgetter(0)))
>>> XX
(1, 1, 5, 7)
>>> YY
(2, 1, 4, 6)

A:

Another idea:
>>> d = dict(zip(Y, X))
>>> sorted(Y, key=d.get)
[6, 3, 4, 7, 2]

You just use corresponding values in X as keys while sorting Y.

