How to sort a list by the number of occurrences in python ?


Examples of how to sort a list by the number of occurrences (repetitions) in python

Sort a list of numbers by the number of occurrences:

To sort a list of numbers by the number of occurrences, a solution is to use the function counter, example:

>>> from collections import Counter
>>> l = [8, 3, 9, 2, 7, 1, 3, 2, 0, 0, 7, 8, 6, 9, 4, 6, 3, 3, 2, 5]
>>> l_sorted = Counter(l).most_common()
>>> l_sorted
[(3, 4), (2, 3), (8, 2), (9, 2), (7, 2), (0, 2), (6, 2), (1, 1), (4, 1), (5, 1)]

the function returns, in descending order, the number with the number of occurrences associated. For example,
number 3 has 4 occurrences in the list. To keep only the numbers:

>>> l_sorted = [i[0] for i in l_sorted]
>>> l_sorted
[3, 2, 8, 9, 7, 0, 6, 1, 4, 5]

Note: to sort in ascending order, a solution is to then use the reverse function:

>>> l_sorted.reverse()
>>> l_sorted
[5, 4, 1, 6, 0, 7, 9, 8, 2, 3]

Sort a list of strings by the number of repetitions

Another example with a list of letters:

>>> from collections import Counter
>>> l = ['a','a','a','b','c','c','d','d','d','d']
>>> l_sorted = Counter(l).most_common()
>>> l_sorted
[('d', 4), ('a', 3), ('c', 2), ('b', 1)]

the function returns, in descending order, the letter with the number of occurrences associated. For example,
the letter 'd' has 4 occurrences in the list. To keep only the numbers:

>>> l_sorted = [i[0] for i in l_sorted]
>>> l_sorted
['d', 'a', 'c', 'b']

Note: to sort in ascending order, a solution is to then use the reverse function:

>>> l_sorted.reverse()
>>> l_sorted
['b', 'c', 'a', 'd']

References