Python – Sort by a particular digit count in elements

When it is required to sort by a particular digit count in elements, a method is defined that takes list element as parameter and uses the ‘count’ and ‘str’ methods to determine the results.

Below is a demonstration of the same −


 Live Demo

def sort_count_digits(elements):
   return str(elements).count(str(my_key))

my_list = [4522, 2452, 1233, 2465]

print("The list is :")

my_key = 2

print("The value of key is ")

my_list.sort(key = sort_count_digits)

print("The result is :")


The list is :
[4522, 2452, 1233, 2465]
The value of key is
The result is :
[1233, 2465, 4522, 2452]


  • A method named ‘sort_count_digits‘ is defined that takes a list element as a parameter.

  • It converts the element into a string and gets the count of it.

  • This is returned as output.

  • A list is defined and displayed on the console.

  • The value for K is defined and is displayed on the console.

  • The list is sorted and the key is specified as the method which was previously defined.

  • This list is the output that is displayed on the console.