What you want is called argsort
in some libraries. In mathematical terms, you want a "permutation" (look it up on wikipedia) that when applied to the input list gives a sorted list.
The best way to do it in Python is the following:
def argsort(lst):
return sorted(range(len(lst)), key=lst.__getitem__)
lst = [15,16,1,2]
print(argsort(lst))
# print: [2, 3, 0, 1]
This is how it works. Instead of sorting the values in lst
, you sort the indexes (range(0, len(lst))
) using the corresponding lst
values as "keys".
Keep in mind that lst.__getitem__(i)
is just equivalent to lst[i]
.
EDIT: for people new to Python and unfamiliar with the "key" argument and the magic methods of Python (those written like __this__
), this may be intimidating. A more friendly versione could be:
def argsort(lst):
indexes = range(len(lst))
return sorted(indexes, key=lambda i: lst[i])