Given the list
List2 = ['Apple', 'Apple', 'Apple', 'Black', 'Black', 'Black', 'Green', 'Green', 'Red', 'Yellow']
I am trying to figure out how to count how many times each element in the list appears. This has to be incredibly simple but I can't figure it out. I read in my book about the count function and I decided to try to implement it. I thought it would be..
for item in List2:
    newlist=[List2.count()] 
I thought this would lead me to what I wanted:
newlist=[3,3,2,1,1]
But I received a TypeError saying count has to have an argument. I'm extremely new to python so dumb everything down as much as possible if you could.
You can use collections.Counter which gives you a dict like object (in that it also has some additional functionality useful for count like purposes) that has key as the item, and a value as the number of occurrences.
from collections import Counter
>>> li = ['Apple', 'Apple', 'Apple', 'Black','Black','Black','Green','Green','Red','Yellow']    
>>> Counter(li)
Counter({'Black': 3, 'Apple': 3, 'Green': 2, 'Yellow': 1, 'Red': 1})
Then it's up to you to sort that how you'd like it presented...
One (inefficient) way to preseve the order, would be to count, then index into the original list:
>>> counts = Counter(li)
>>> [counts[key] for key in sorted(counts, key=li.index)]
[3, 3, 2, 1, 1]
An alternative is to use groupby (but this relies on the items being consecutive):
>>> from itertools import groupby
>>> [len(list(g)) for k, g in groupby(li)]
[3, 3, 2, 1, 1]
                        If you're new to Python I think that is better for you to code the solution instead of just importing something. Here's a simple and easy to understand way to do it:
counter = {}
for elem in List2:
    counter[elem] = counter.get(elem, 0) + 1
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With