This article tackles the simple and powerful ways to sort a list of items and use the lambda function inside the
sort() method. We also discuss why we failed to execute Python’s
Correct Way to Use Key Argument Inside the
sort() Method in Python
Ordered data lies at the heart of many web services. When we perform a search, the algorithm returns an ordered list of relevant results, and when shopping online, we often want to sort products by price.
When we look at our calendar, we expect our appointments to be sorted in chronological order.
Let’s start with a classic example and sort alphabetically. We’ll use a list of six alkaline earth metals.
They are sorted by atomic number, but what if we wanted to sort them alphabetically? For lists, we call the
sort() method assumes you want the data sorted alphabetically, in ascending order. If you want to sort the data in reverse order, you call the
sort() method and specify
Earth_Metals=["Berylium","Magnisium","Calcium","strontium","Barium","Radium"] Earth_Metals.sort() print(Earth_Metals)
If you look at the list, the names are sorted in reverse alphabetical order.
['Barium', 'Berylium', 'Calcium', 'Magnisium', 'Radium', 'strontium']
Let’s repeat this example, except this time, we store the elements in a tuple rather than a list. When we try to sort a tuple, Python complains and raises an exception.
The reason for this error is that tuples are immutable objects. They cannot be changed, and sorting changes things.
Earth_Metals=("Berylium","Magnisium","Calcium","strontium","Barium","Radium") Earth_Metals.sort() print(Earth_Metals)
AttributeError: 'tuple' object has no attribute 'sort'
Before we see a more complex example, let’s look at the
help() text for the
sort method on lists.
The sort method accepts two keyword arguments, the
reverse. By default, the
reverse is set to
false, which means the data will be sorted in ascending order.
Let’s focus on the
key argument where the action lies. To use the key argument, you pass in a function that will be used to determine what values to sort by.
Suppose we are building an application for processing orders, and we have this list of order items, and in every item in this list is a tuple with two items the product name and its price. Let’s see what will happen if we sort this list and print the items.
items=[("product1",10), ("product2",9), ("product3",12)] items.sort() print(items)
[('product1', 10), ('product2', 9), ('product3', 12)]
Nothing changes when we execute the code because Python does not know how to sort this list. In this situation, we need to define Python’s function for sorting lists.
We will make it cleaner by using a lambda expression or an anonymous function, so we do not have to define this function first and then pass it. Instead of this, we add lambda, and the syntax for writing a lambda function is like this we add parameters colon and then expression.
We will have only one parameter; then, after the colon(
:), we are returning an item of one.
items=[("product1",10), ("product2",9), ("product3",12)] items.sort(key=lambda item:item) print(items)
[('product2', 9), ('product1', 10), ('product3', 12)]
Some beginners try to give more than one argument value to the
key argument and get an error because the
key argument only accepts one value. Another reason we failed to execute the code was that we directly passed the function instead of using the