This can be done in linear O(n) time with the help of a dict:
l = ['a','b','c','d','e','f','g','h','i','j']
m = [ 1, 4, 5, 9, 2, 6, 3, 7, 8, 10]
values_by_index = dict(zip(m, l))
result = [values_by_index[index+1] for index in range(len(m))]
print(result)
# output: ['a', 'e', 'g', 'b', 'c', 'f', 'h', 'i', 'd', 'j']
The first line creates dict that maps indices to values, which looks like this:
>>> values_by_index
{1: 'a', 4: 'b', 5: 'c', 9: 'd', 2: 'e', 6: 'f', 3: 'g', 7: 'h', 8: 'i', 10: 'j'}
In the second line we simply loop over the indices 1 through 10 and grab the corresponding value from the dict, which is a O(1) operation in the average case.
If you have 0-based indices, simply remove the +1
from index+1
.