
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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
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.
- Related Articles
- Python - Sort Matrix by Maximum Row element
- Python program to Sort Tuples by their Maximum element
- Python – Sort by Units Digit in a List
- Python – Sort by a particular digit count in elements
- Python – Sort Matrix by Maximum String Length
- Python – Sort Matrix by K Sized Subarray Maximum Sum
- Python program to sort a tuple by its float element
- Consecutive element maximum product in Python
- Maximum element in tuple list in Python
- Python Program to sort rows of a matrix by custom element count
- Python – Sort Matrix by Number of elements greater than its previous element
- Sort Array By Parity in Python
- Python – Maximum of K element in other list
- Python – Sort by range inclusion
- Python – Sort by Uppercase Frequency

Advertisements