Create new list with the count of occurrences for each element in an objective list

  • A+

New to Python here.

I am looking for a simple way of creating a list (Output), which returns the count of the elements of another objective list (MyList) while preserving the indexing(?).

This is what I would like to get:

MyList = ["a", "b", "c", "c", "a", "c"] Output = [ 2 ,  1 ,  3 ,  3 ,  2 ,  3 ] 

I found solutions to a similar problem. Count the number of occurrences for each element in a list.

In  : Counter(MyList) Out : Counter({'a': 2, 'b': 1, 'c': 3}) 

This, however, returns a Counter object which doesn't preserve the indexing.

I assume that given the keys in the Counter I could construct my desired output, however I am not sure how to proceed.

Extra info, I have pandas imported in my script and MyList is actually a column in a pandas dataframe.


You can use the list.count method, which will count the amount of times each string takes place in MyList. You can generate a new list with the counts by using a list comprehension:

MyList = ["a", "b", "c", "c", "a", "c"]  [MyList.count(i) for i in MyList] # [2, 1, 3, 3, 2, 3] 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: