Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python – Sort by Units Digit in a List
When sorting a list by its units digit (last digit), we can use a custom key function with the sort() method. This function converts each number to a string and extracts the last character using negative indexing.
Using a Custom Key Function
The most straightforward approach is to define a helper function that extracts the units digit ?
def unit_sort(element):
return str(element)[-1]
numbers = [716, 134, 343, 24742]
print("The list is:")
print(numbers)
numbers.sort(key=unit_sort)
print("The result is:")
print(numbers)
The list is: [716, 134, 343, 24742] The result is: [24742, 343, 134, 716]
Using Lambda Function
For a more concise approach, we can use a lambda function instead of defining a separate function ?
numbers = [716, 134, 343, 24742, 89, 105]
print("Original list:", numbers)
# Sort by units digit using lambda
numbers.sort(key=lambda x: str(x)[-1])
print("Sorted by units digit:", numbers)
Original list: [716, 134, 343, 24742, 89, 105] Sorted by units digit: [343, 134, 105, 716, 24742, 89]
Using Modulo Operator
Alternatively, we can use the modulo operator to get the units digit mathematically ?
numbers = [716, 134, 343, 24742, 89, 105]
print("Original list:", numbers)
# Sort by units digit using modulo
numbers.sort(key=lambda x: x % 10)
print("Sorted by units digit:", numbers)
Original list: [716, 134, 343, 24742, 89, 105] Sorted by units digit: [343, 134, 105, 716, 24742, 89]
How It Works
The sorting process works as follows:
The
sort()method uses thekeyparameter to determine sorting criteriaFor each element, the key function extracts the units digit
String method:
str(element)[-1]converts to string and gets the last characterModulo method:
element % 10gives the remainder when divided by 10Elements are sorted based on these extracted digits
Comparison
| Method | Syntax | Performance | Best For |
|---|---|---|---|
| String indexing | str(x)[-1] |
Slower (string conversion) | Readability |
| Modulo operator | x % 10 |
Faster (no conversion) | Performance |
| Lambda function | lambda x: x % 10 |
Fast + concise | One-time use |
Conclusion
Use the modulo operator x % 10 for better performance, or string indexing str(x)[-1] for readability. Lambda functions provide a concise solution for one-time sorting operations.
