Remove duplicates from a python list so that the last instance remains

Let’s say I have the following list:

start = [1, 2, 3, 1, 3, 4, 5, 3, 2]

I want to remove the duplicates so that the last instance remains. So the result would be:

result = [1, 4, 5, 3, 2]

I’ve written the following function:

def keep_last_instances(start):
    result = []
    
    total_counts = Counter(start)
    current_counts = {}
    for x in start:
        total_count = total_counts[x]
        current_count = current_counts.get(x, 0) + 1

        if current_count == total_count:
            result.append(x)
        else:
            current_counts[x] = current_count
    
    return result

Is there a faster/cleaner way?

Answer

Option 1, O(n) + O(k log k) time, O(n) storage, where k is the number of unique keys.

nums = [1, 2, 3, 1, 3, 4, 5, 3, 2]
mapping = {n: i for i, n in enumerate(nums)}
return sorted(mapping.keys(), key=mapping.get)

Option 2, O(n) time, O(n) storage:

seen = set()
result = collections.deque()

for i in range(len(nums) - 1, -1, -1):
    if nums[i] not in seen:
        seen.add(nums[i])
        result.appendleft(nums[i])
return result