How to replace every element in a list with the position where that element first appeared in Python

1 Answer

0 votes
def replace_each_element_with_ordinal_first_occurrence(lst):
    first_index = {}
    result = []

    for i, x in enumerate(lst, start=1):
        if x not in first_index:
            first_index[x] = i
        result.append(first_index[x])

    return result

    
lst = ["a", "b", "c", "c", "b", "c", "d", "e", "f", "g", "f"]

result = replace_each_element_with_ordinal_first_occurrence(lst)

print(result)



'''
run:
 
[1, 2, 3, 3, 2, 3, 7, 8, 9, 10, 9]
 
'''
 

 



answered Feb 14 by avibootz
...