Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,939 questions

51,876 answers

573 users

How to replace each element in a list with its ordinal only the first time it appears using Python

1 Answer

0 votes
def replace_each_element_with_ordinal_first_time(lst):
    seen = set()
    result = []

    for i, x in enumerate(lst, start=1):
        if x not in seen:
            result.append(i)
            seen.add(x)
        else:
            result.append(x)

    return result

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

result = replace_each_element_with_ordinal_first_time(lst)

print(result)



'''
run:
 
[1, 2, 3, 'c', 'b', 6, 7, 8, 9, 'f']
 
'''
 

 



answered 9 hours ago by avibootz

Related questions

...