Sometimes we might need to sort lists in Python programming. This article will discuss Python list sorting methods.
Using list.sort method
Python lists have a built-in sort method it modifies the list in place.
The syntax of the list.sort method
sort(*, key=None, reverse=False)
Parameters
- key : Callable function that takes a single argument
- reverse : a boolean value to indicate comparison in reverse
Let’s see some examples of list.sort method.
numbers = [10,1,500,20,70,60,8,122]
numbers.sort()
print(numbers)
Output
[1, 8, 10, 20, 60, 70, 122, 500]
Reverse sorting by passing reverse=True to sort method. The list will be sorted in descending order.
numbers = [10,1,500,20,70,60,8,122]
numbers.sort(reverse=True)
print(numbers)
Output
[500, 122, 70, 60, 20, 10, 8, 1]
Using sorted function
The sorted built-in function can be used to sort lists.
The syntax of the sorted function
sorted(iterable, key=None, reverse=False)
The sorted function has two optional arguments that must be specified as keyword arguments.
Parameters
- key : Callable function that takes single argument
- reverse : a boolean value to indicate comparison in reverse
Returns
A new sorted list with the items in the iterable
Let’s see some examples of Python list sorting using the sorted function.
numbers = [10,1,500,20,70,60,8,122]
sorted_nums = sorted(numbers)
print(numbers)
print(f"Sorted list - {sorted_nums}")
Output
[10, 1, 500, 20, 70, 60, 8, 122]
Sorted list - [1, 8, 10, 20, 60, 70, 122, 500]]
Reverse sort order
numbers = [10,1,500,20,70,60,8,122]
sorted_nums = sorted(numbers,reverse = True)
print(numbers)
print(f"Sorted list - {sorted_nums}")
Output
[10, 1, 500, 20, 70, 60, 8, 122]
Sorted list - [500, 122, 70, 60, 20, 10, 8, 1
Key functions in sorted/list.sort()
The key parameter is a function or callable. The sort function will call the key function on each element before comparison.
message = "This is a test message from NoloWiz"
sorted_message = sorted(message.split(),key=str.lower)
print(sorted_message)
Output
['a', 'from', 'is', 'message', 'NoloWiz', 'test', 'This']
We have used str.lower as key function.
Sorting tuples
In this example, we will sort employees’ tuples based on their salary.
employees = [
('Tony', 'developer', 1000),
('Robert', 'tester', 800),
('Ram', 'manager', 4000),
]
employees_sorted = sorted(employees, key =lambda employee: employee[2]) #sort salary
print(employees_sorted)
Output
[('Robert', 'tester', 800), ('Tony', 'developer', 1000), ('Ram', 'manager', 4000)]
Sort class objects
In this example, we will create a list of objects and sort.
class Employee:
def __init__(self, name, desig, salary):
self.name = name
self.designation = desig
self.salary = salary
def __repr__(self):
return repr((self.name, self.designation, self.salary))
employee_objects = [
Employee('Tony', 'developer', 1000),
Employee('Robert', 'tester', 800),
Employee('Ram', 'manager', 4000),
]
employees_sorted = sorted(employee_objects, key=lambda employee: employee.salary) # sort by salary
print(employees_sorted)
Output
[('Robert', 'tester', 800), ('Tony', 'developer', 1000), ('Ram', 'manager', 4000)]
Using itemgetter itemgetter(), attrgetter() with sorting
The operator module has itemgetter(), attrgetter() funtions,so instead of using lambda expression we can use itemgetter/attrgetter functions as key function.
from operator import itemgetter, attrgetter
employees_sorted = sorted(employees, key=itemgetter(2))
print(employees_sorted)
Output
[('Robert', 'tester', 800), ('Tony', 'developer', 1000), ('Ram', 'manager', 4000)]
Let’s see an example of object sorting using attrgetter.
from operator import itemgetter, attrgetter
employees_sorted = sorted(employee_objects, key=attrgetter("salary"))
print(employees_sorted)
Output
[('Robert', 'tester', 800), ('Tony', 'developer', 1000), ('Ram', 'manager', 4000)]
Here attrgetter function used to get employee object’s attribute “salary”.
Conclusion
These are the different ways to sort lists in Python. Read remove list duplicates.