from collections import defaultdict, deque indexes = defaultdict(deque) for i, x in enumerate(lst2): indexes[x].append(i) ids = [indexes[x].popleft() for x in lst1]