Python – Sort by Maximum digit in Element


When it is required to sort by maximum digit in element, a method is defined that uses ‘str’ and ‘max’ method to determine the result.

Below is a demonstration of the same −

Example

 Live Demo

def max_digits(element):
   return max(str(element))

my_list = [224, 192, 145, 18, 3721]

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

my_list.sort(key = max_digits)

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

Output

The list is :
[224, 192, 145, 18, 3721]
The result is :
[224, 145, 3721, 18, 192]

Explanation

  • A method named ‘max_digits’ is defined that takes element as a parameter, and converts it into a string, and then gets the maximum of it, and returns this as output.

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

  • The list is sorted using ‘sort’ method and the key is specified as the previously defined method.

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

Updated on: 06-Sep-2021

94 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements