Search code examples
pythonlistcountunique

Python - make non-unique items in list unique by adding count


How would I make the items in my list unique by concatenating a count, starting from 1 for each unique value?

so, for example:

sheep, sheep, tiger, sheep, hippo, tiger

becomes:

sheep1, sheep2, tiger1, sheep3, hippo1, tiger2


Solution

  • Here's how you could use Counter to do it.

    from collections import Counter
    
    s = ["sheep", "sheep", "tiger", "sheep", "hippo", "tiger"]
    u = [ f"{a}{c[a]}" for c in [Counter()] for a in s if [c.update([a])] ]
    
    print(u)
    
    ['sheep1', 'sheep2', 'tiger1', 'sheep3', 'hippo1', 'tiger2']
    

    note that, if your strings can have a numeric suffix, this would not be sufficient to cover all cases (e.g. ['alpha']*11+['alpha1'] would repeat 'alpha11')