- 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 Advanced Tutorial
- Python - Classes/Objects
- Python - Reg Expressions
- Python - CGI Programming
- Python - Database Access
- Python - Networking
- Python - Sending Email
- Python - Multithreading
- Python - XML Processing
- Python - GUI Programming
- Python - Further Extensions
Python â€“ Sort by Units Digit in a List
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.
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)
The list is : [716, 134, 343, 24742] The result is : [24742, 343, 134, 716]
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.
- Related Articles
- Python â€“ Sort by Maximum digit in Element
- Python â€“ Sort by a particular digit count in elements
- Python â€“ Sort a List by Factor count
- Python â€“ Sort by Rear Character in Strings List
- Sort list of tuples by specific ordering in Python
- Python â€“ Sort String list by K character frequency
- Ways to sort list of dictionaries by values in Python
- Python program to sort a list of tuples by second Item
- Python Program to Sort A List Of Names By Last Name
- How can I sort one list by values from another list in Python?
- Python â€“ Sort Dictionary List by Keyâ€™s ith Index value
- Ways to sort list of dictionaries by values in Python Using itemgetter
- SI Units List
- How do I sort a list of dictionaries by values of the dictionary in Python?
- Python â€“ Sort given list of strings by numeric part of string