
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 List by Units Digit in Python
When it is required to sort by units digit in a list, a method is defined that takes one parameter and uses ‘str’ and negative indexing to determine the output.
Example
Below is a demonstration of the same −
def unit_sort(element): return str(element)[-1] my_list = [716, 134, 343, 24742] print("The list is :") print(my_list) my_list.sort(key=unit_sort) print("The result is :") print(my_list)
Output
The list is : [716, 134, 343, 24742] The result is : [24742, 343, 134, 716]
Explanation
A method named ‘unit_sort’ is defined that takes an element of list as a parameter, and returns the last element after converting it to string as output.
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