The Python Oracle

How to count the frequency of the elements in an unordered list?

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Ominous Technology Looping

--

Chapters
00:00 How To Count The Frequency Of The Elements In An Unordered List?
00:22 Answer 1 Score 52
00:37 Answer 2 Score 173
00:56 Answer 3 Score 37
01:11 Accepted Answer Score 651
01:41 Thank you

--

Full question
https://stackoverflow.com/questions/2161...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #list #frequency

#avk47



ACCEPTED ANSWER

Score 651


In Python 2.7 (or newer), you can use collections.Counter:

>>> import collections
>>> a = [5, 1, 2, 2, 4, 3, 1, 2, 3, 1, 1, 5, 2]
>>> counter = collections.Counter(a)
>>> counter
Counter({1: 4, 2: 4, 5: 2, 3: 2, 4: 1})
>>> counter.values()
dict_values([2, 4, 4, 1, 2])
>>> counter.keys()
dict_keys([5, 1, 2, 4, 3])
>>> counter.most_common(3)
[(1, 4), (2, 4), (5, 2)]
>>> dict(counter)
{5: 2, 1: 4, 2: 4, 4: 1, 3: 2}
>>> # Get the counts in order matching the original specification,
>>> # by iterating over keys in sorted order
>>> [counter[x] for x in sorted(counter.keys())]
[4, 4, 2, 1, 2]

If you are using Python 2.6 or older, you can download an implementation here.




ANSWER 2

Score 173


If the list is sorted, you can use groupby from the itertools standard library (if it isn't, you can just sort it first, although this takes O(n lg n) time):

from itertools import groupby

a = [5, 1, 2, 2, 4, 3, 1, 2, 3, 1, 1, 5, 2]
[len(list(group)) for key, group in groupby(sorted(a))]

Output:

[4, 4, 2, 1, 2]



ANSWER 3

Score 52


Count the number of appearances manually by iterating through the list and counting them up, using a collections.defaultdict to track what has been seen so far:

from collections import defaultdict

appearances = defaultdict(int)

for curr in a:
    appearances[curr] += 1



ANSWER 4

Score 37


In Python 2.7+, you could use collections.Counter to count items

>>> a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
>>>
>>> from collections import Counter
>>> c=Counter(a)
>>>
>>> c.values()
[4, 4, 2, 1, 2]
>>>
>>> c.keys()
[1, 2, 3, 4, 5]