
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sort Python List 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.
Advertisements