Python 3 Count elements in ordered list

Below you can see how to find the element frequency in a python ordered list. The output is a dictionary showing the element and it's frequency in the list:

from itertools import groupby
ordered_list = [1,1,1,2,2,2,2,2,3,3,3,4,4,4,5,5]
print({key:len(list(group)) for key, group in groupby(ordered_list)})

result:

{1: 3, 2: 5, 3: 3, 4: 3, 5: 2}

Note that this example will not work correctly if the list is not sorted.

Python 3 Count elements in unordered list

Very often you will need to count the elements of a list with heterogeneous elements. Sometimes the sort operation will be not applicable or not well suited for your example (if you need to keep the order of the elements). In this case you can use count for unordered lists: