Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Given a list, How to count items in that list?

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.

like image 427
Bob Avatar asked Oct 31 '25 08:10

Bob


2 Answers

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]
like image 189
Jon Clements Avatar answered Nov 01 '25 23:11

Jon Clements


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
like image 32
juliomalegria Avatar answered Nov 01 '25 23:11

juliomalegria



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!