Consider the following list:
employees = ['Bill Gates', 'Mark Zukerberg', 'Jeff Bezos', 'Elon Musk', 'Larry Page']
To sort the list employees
employees.sort()
Output
['Bill Gates', 'Elon Musk', 'Jeff Bezos', 'Larry Page', 'Mark Zukerberg']
As we can see here the normal sorting sort the elements by alphabets. Let's say we want to sort the list by the length of each string element in the list. We can easily do that using the key
parameter of the sort method.
To sort the original list employees
by the length of elements
employees.sort(key=len)
print(employees)
Output
['Elon Musk', 'Bill Gates', 'Jeff Bezos', 'Larry Page', 'Mark Zukerberg']
In the example above we are passing a built-in len()
method to sort the list by the length of elements. We can also supply our custom sort function as well instead of a built-in function.
This key
function takes each element of the list, transforms it and return one value which is then used to sort the list.
sort()
sorts a list in-place in ascending or descending order. sort()
method takes two parameters which are both optional:
- key: function which serves as the basis for comparison.
- reverse: if
True
, then it will sort the list in descending order, otherwise in ascending order. Defaults toFalse
.
Syntax
list.sort(key=..., reverse=...)
Let's look at another example of sorting a list of tuples using the second element:
cart =[('Mango', 5), ('Grapes', 10), ('Banana', 3), ('Melon', 5), ('Strawberry', 7)]
To sort the cart
list using the second element of each tuple
cart.sort(key=lambda x : x[1])
print(cart)
Output
[('Banana', 3), ('Mango', 5), ('Melon', 5), ('Strawberry', 7), ('Grapes', 10)]
There is one more method that is used to sort the iterable called sorted()
.
sorted()
returns a sorted list of elements in ascending or descending order.
It takes 3 parameters:
- iterable: Either a sequence of elements like list, string or tuple or a collection like dict, set etc.
- key (optional): function which serves as the basis for comparison.
- reverse (optional): if
True
, then it will sort the iterable in descending order, otherwise in ascending order. Defaults toFalse
.
Syntax
sorted(iterable, key=..., reverse=...)
Top comments (0)