
- 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 List items on basis of their Digits
When it is required to sort the elements of a list based on the digits, the ‘max’, ‘max’ method are used. We will also use the ‘sorted’ method, the ‘lambda’ function and ‘ljust’.
Example
Below is a demonstration of the same −
my_list = [4344, 2611, 122, 541, 33, 892, 48292, 460, 390, 120, 10, 2909, 11239, 1] print("The list is : " ) print(my_list) print("The list after sorting is : " ) my_list.sort() print(my_list) my_temp_val = map(str, my_list) my_max_length = max(map(len, my_temp_val)) my_result = sorted(my_list, key = lambda index : (str(index).ljust(my_max_length, 'a'))) print("The resultant list is : ") print(my_result)
Output
The list is : [4344, 2611, 122, 541, 33, 892, 48292, 460, 390, 120, 10, 2909, 11239, 1] The list after sorting is : [1, 10, 33, 120, 122, 390, 460, 541, 892, 2611, 2909, 4344, 11239, 48292] The resultant list is : [10, 11239, 120, 122, 1, 2611, 2909, 33, 390, 4344, 460, 48292, 541, 892]
Explanation
A list of strings is defined and is displayed on the console.
The list is sorted using a sort method and is displayed on the console.
The ‘map’ method is used to convert all elements in the list to a string.
This is assigned to a variable
The maximum of the elements in the list is found and assigned to a variable.
The sorted method is used to sort the list, and the key is the lambda function with the left justification.
This is assigned to a result.
This is displayed as output on the console.
- Related Articles
- Python – Sort List items on the basis of their Digits
- Program to update list items by their absolute values in Python
- Sort the numbers according to their sum of digits in C++
- Python program to Sort a List of Dictionaries by the Sum of their Values
- Python – Sort Tuples by Total digits
- Sort Tuples by Total digits in Python
- Program to sort out phrases based on their appearances in Python
- Python | Sum of number digits in List
- Convert list of tuples into digits in Python
- Extract digits from Tuple list Python
- Python | Sort the values of first list using second list
- Python - Create nested list containing values as the count of list items
- Python How to sort a list of strings
- Differentiate between metal and non-metal on the basis of their chemical properties.
- Differentiate between parenchyma, collenchyma, and sclerenchyma on the basis of their cell walls.

Advertisements