# Python – Sort List items on the basis of their Digits

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

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.

Updated on 08-Sep-2021 08:16:52