B. Smith
B. Smith

Reputation: 1

Count number of occurrences for each item in a list

I want to count how many times each item is displaying in a list. Here is what I have:

for i in range(len(alist)):
    print(alist[i], alist.count(i))

The issue with this right now is that if the list has for example 7 of the same occurrences, it is printing

a 0
a 0
a 0 
a 0
a 0
a 0
a 0

rather than what I want which is

a 7

Upvotes: 0

Views: 2164

Answers (3)

Paweł Michoń
Paweł Michoń

Reputation: 35

Use collections.defaultdict(int)

When you do this:
my_dict = defaultdict(int)

Every element that's being added to that dictionary will have default value of 0 e.g

my_list=["a","a","b","a","b"]
my_dict = defaultdict(int)

for e in my_list:
   my_dict[e]
print(my_dict)

Output: {'a': 0, 'b': 0}

If you want to count amount of each element just increase counter by one when iterating through list

my_list=["a","a","b","a","b"]
my_dict = defaultdict(int)

for e in my_list:
    my_dict[e]+=1

Output: {'a': 3, 'b': 2}

Great explanation video: https://www.youtube.com/watch?v=Sah0p4ILGRE&t=33s

Upvotes: 1

cjauvin
cjauvin

Reputation: 3703

You could use a collections.Counter for that:

from collections import Counter

cnt = Counter(['a', 'a', 'b', 'a'])
print(cnt)  # Counter({'a': 3, 'b': 1})

Because a Counter is a dict underneath, you can then do:

for char, count in cnt.items(): 
    print(char, count)

# a 3
# b 1

Upvotes: 4

PeptideWitch
PeptideWitch

Reputation: 2359

You've declared the value of i as an integer, so you need to count the list entry of i, not i itself.

print(alist[i], alist.count(alist[i]))

Alternatively, I'd suggest:

your_list = ['A', 'B', 'A', 'C', 'A']
for item in set(list):
    print(f'{item} occurs {your_list.count(item)} number of times.')

This makes your code more readable :) set(list) will return a set, i.e. all unique values within the list. Or you can use numpy.unique() to the same effect.

Upvotes: 1

Related Questions