I have a list of non-unique values. I want to output a list of the same length where each value corresponds to how many times that value has appeared so far.The code I have written to do this seems over-complicated, so I think there has to be a better way.x = [1,1,2,3,1,3]def times_so_far(ls):    out = [0]*len(x)    counted = {}    for i,v in enumerate(x):        if v in counted:            counted[v] += 1        else:            counted[v] = 0        out[i] = counted[v]    return outtimes_so_far(x)#[0, 1, 0, 0, 2, 1]
Count how many times values has appeared in list so far
python;algorithm
Maybe using list.count() you can achieve the same with less lines?x = [1,1,2,3,1,3]def times_so_far(ls):    out = [0]*len(ls)    for i in xrange(len(ls)):        out[i] = ls[:i].count(ls[i])     return outThis can be written with list comprehension as mentioned by Caridorc, and it removes the first len(ls) call this way (though maybe at the cost of resizing out for every element of the list):def times_so_far(ls):    return [ls[:i].count(ls[i]) for i in xrange(len(ls))]Now, if you're going to work with lists of positive integers of a small value, I would recommend the following, as it's similar to yours but it works with indices instead of dict keys:def times_so_far(ls, maxValue):   temp = [0]*(maxValue+1)   out = [0]*len(ls)   for i in xrange(len(ls)):      out[i] = temp[ls[i]]      temp[ls[i]] += 1   return out