Arrange a number when max count has equal occurrences

I have a list (my_list), and i arranged the list according to most common occurance.

pythonmy_list = [1,3,3,5,5,2,1,1]

#arrage according to most common occurances from collections import Counter a=([k for k, s in Counter(my_list).most_common()]) print(a)

And the output is [1, 3, 5, 2]. since there are three 1, two 3 and 5, and just one 2 in the list

Even though both 3 and 5 has equal numbers in the list, but in the output it came numerically , and 3 came before 5. Is there a way, where a value i provide will be at the front when there’s equal occurance. For example i provide a variable number = 5, and in the output list 5 will come before 3? And output will be [1, 5, 3, 2]

Define your own key function and pass that to sorted.

As suggested by others simple key function for prioritization should be enough:

from collections import Counter


data = [1,0,0,3,3,5,5,2,1,1]

def my_sort(list_, priority=None):
    freq = Counter(list_)
    def keyfunc(num):
        if num == priority:
            return (freq[num], 1)
        return (freq[num], 0)
    return sorted(freq, key=keyfunc, reverse=True)

print(my_sort(data))
print(my_sort(data, priority=5))

# [1, 0, 3, 5, 2]
# [1, 5, 0, 3, 2]