# Python – Sort by a particular digit count in elements

PythonServer Side ProgrammingProgramming

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 −

## Example

Live Demo

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

my_list = [4522, 2452, 1233, 2465]

print("The list is :")
print(my_list)

my_key = 2

print("The value of key is ")
print(my_key)

my_list.sort(key = sort_count_digits)

print("The result is :")
print(my_list)

## Output

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

## Explanation

• 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.

Published on 06-Sep-2021 08:05:44