An alternative approach to the index method is to build a dictionary of the locations in one pass instead of searching through the list each time. If the list is long enough, this should be faster, because it makes the process linear in the number of elements (on average) instead of quadratic. To be specific, instead of
def index_method(la, lb): return [lb.index(i) for i in la]
you could use
def dict_method(la, lb): where = {v: i for i,v in enumerate(lb)} return [where[i] for i in la]
This should be roughly comparable on small lists, albeit maybe a little slower:
>>> list_a = ['s{}'.format(i) for i in range(5)] >>> list_b = list_a[:] >>> random.shuffle(list_b) >>> %timeit index_method(list_a, list_b) 1000000 loops, best of 3: 1.86 µs per loop >>> %timeit dict_method(list_a, list_b) 1000000 loops, best of 3: 1.93 µs per loop
But it should be much faster on longer ones, and the difference will only grow:
>>> list_a = ['s{}'.format(i) for i in range(100)] >>> list_b = list_a[:] >>> random.shuffle(list_b) >>> %timeit index_method(list_a, list_b) 10000 loops, best of 3: 140 µs per loop >>> %timeit dict_method(list_a, list_b) 10000 loops, best of 3: 20.9 µs per loop