Computer >> Computer tutorials >  >> Programming >> Python

Python – Sort List items on the basis of their Digits


When it is required to sort list items based on their digits, a method is defined that uses list comprehension and ‘sum’ method to determine the output.

Example

Below is a demonstration of the same −

def sort_list_digit(my_list):
   digits = [int(digit) for digit in str(my_list) ]
   return sum(digits)

my_list = [124, 20, 106, 35, 44]

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

print("The result is :")
print(sorted(my_list, key = sort_list_digit))

Output

The list is :
[124, 20, 106, 35, 44]
The result is :
[20, 124, 106, 35, 44]

Explanation

  • A method named ‘sort_list_digit’ is defined that takes a list as a parameter.

  • It uses list comprehension to iterate over the elements, and convert every element to an integer.

  • It then returns sum of the digits of the elements in the list as output.

  • Outside the method, a list of integers is defined and is displayed on the console.

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

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