Different Ways of Using Sorted Function in Python

Sorted() function using a key parameter in Python

Photo by Sophie Elvis on Unsplash

Different Ways of Using Sorted Function in Python

Sorted(): Sorted function will return new sorted list of the iterable object(list,dictionary,tuple). By default, it will sort in ascending order.

Strings-Sorting is done based on ASCII values.

Return type: List

Syntax:

sorted(iterable,key=None,reverse=False)

iterable :string,list,tuple,set,dictionary

key(Optional): If we specify key, it will sort the iterable based on the function specified in the key.

reverse(Optional): By default, it will sort the iterable in ascending order. If reverse=True, it will sort the iterable in descending order.

https://gist.github.com/IndhumathyChelliah/f5a75ec9eeeb5e364fe54b867da84449

Key parameter

We can also sort the iterable based on the function specified in the key parameter. It can be

  • Built-in function
  • User-defined function
  • Lambda function
  • itemgetter
  • attrgetter

1. Built-in function

len()-It will count the length of the object. If we specify len as a key parameter in the sorted function, it will sort the iterable based on the length.

https://gist.github.com/IndhumathyChelliah/02680982e7bb39265f59ba377f49d4b2

abs()– It will return the absolute value of a number. If we specify abs as a key parameter, it will sort based on the absolute value.

https://gist.github.com/IndhumathyChelliah/9873703027f2d241ad85708814b66a70

str.lower()-str.lower() will convert all uppercase characters to lower case.If we mention key as str.lower, it will perform lower on all items present in the iterable, and then sort it.

https://gist.github.com/IndhumathyChelliah/5d692001b83e991fa4c2bed65b5387d7

2. User-Defined Function

We can specify the key as user-defined functions also. It will sort the iterable based on user-defined function.

Example 1: By default, the sorted function will sort a list of tuples based on the first element. Here we mentioned a user-defined function to take the second element. So, now sorted function sort the list of tuples based on the second element

https://gist.github.com/IndhumathyChelliah/c58dcbd87385ee3eb094d96a576bf6c2

Example 2: We can sort a list of class objects by specifying user-defined functions.

In the below example,

  • Class Student has three attributes name,rollno, grade.
  • Created 3 Student objects s1,s2,s3
  • Created list s4 containing all three Student objects(s1,s2,s3)
  • Now have to sort the list of Student objects
  • Defined function(sort_key) to return the attribute rollno.
  • In sorted function, mentioned key as user-defined function(sort_key)
  • Now sorted(), returns a list of Student objects sorted by rollno.

https://gist.github.com/IndhumathyChelliah/d404fd5d078e940e17c124a626219728

Note: If we didn’t specify key for sorting class objects, it will raise TypeError. Since, it doesn't know on what basis to sort the class objects.

3.lambda function

We can mention the key as lambda function also. Based on that lambda function, sorted() will sort the iterable.

Example 1: Sorting list of class objects based on the lambda function mentioned in the key parameter.

https://gist.github.com/IndhumathyChelliah/2a9536b110694e71e595d94c46ff7ebb

Example 2: Sorting list of tuples based on the second element in the tuple. Lambda function which returns the second element is mentioned as key.

https://gist.github.com/IndhumathyChelliah/3e02107d5146602242c412dd657819a4

4.itemgetter

operator is a built-in module that contains many operators. itemgetter(n) constructs a function that assumes an iterable object (e.g. list, tuple, set) as input, and fetches the n-th element out of it.

Example:1 Sorting list of tuples based on the third element in the tuple. itemgetter() will return the function that fetches the third element in the tuple.

By default, if we didn’t specify the key, it will sort based on the first element in the tuple.

from operator import itemgetter
l1=[(1,2,3),(3,1,1),(8,5,3),(3,4,2)]

#Sorted based on third element in the tuple.
print (sorted(l1,key=itemgetter(2)))
#Output:[(3, 1, 1), (3, 4, 2), (1, 2, 3), (8, 5, 3)]

Example:2 Sorting list of dictionaries based on the key(age) in the dictionary.

https://gist.github.com/IndhumathyChelliah/d9b3cbaf3a67ab90afa438ba97ac9c8a

Example:3 Sorting dictionary values using itemgetter.

https://gist.github.com/IndhumathyChelliah/938e032257b6b3d2229e1badf653a9d7

5. attrgetter

operator.attrgetter (attr)
operator. attrgetter (*attrs)

Return a callable object that fetches attr from its operand. If more than one attribute is requested, returns a tuple of attributes. The attribute names can also contain dots.

Example: Sorting list of class objects by using attrgetter. attrgetter function can get the attribute of the object and the sorted function will sort based on that attribute.

https://gist.github.com/IndhumathyChelliah/b8267f28e86110f86bd3c95319987858

Multiple level sorting

  • We can do multiple level sorting by itemgetter also.

In the below example, it will sort the dictionary values based on the second element. In case if the second element is equal, then it will sort based on the third element.

https://gist.github.com/IndhumathyChelliah/8f6c0ea0dba1635a8f02cad0299932e4

  • multiple levels sorting by using the lambda function in the key parameters.

In the below example, it will sort the list of tuples based on the second element, if the second element is equal means it will sort based on the third element.

https://gist.github.com/IndhumathyChelliah/5a65a05960acfc59c3da5c2f192261cb

Mixed data types

sorted function doesn’t support mixed data types. It will raise TypeError.

https://gist.github.com/IndhumathyChelliah/c0d050df3fa03a37c0a37f2b0b63d859


Conclusion

1. When sorting a list of class objects, the key is a must. If we didn’t mention the key, it will raise TypeError.
2. For sorting a list of class objects, we can use user-defined function/lambda function/attrgetter as a key parameter.
3. sorted() function-Return type is List
4. sort method will sort the original list itself. the sorted function will return a new list. It won’t modify the original list.
5. sort method is used to sort only list. sort method is not available for string, tuple, dictionary.


My other blog links

How to Use Key Function in Max() and Min() in Python

Resources(Python Documentation)

operator

itemgetter

attrgetter

sorting

One-Time
Monthly
Yearly

Make a one-time donation

Make a monthly donation

Make a yearly donation

Choose an amount

$5.00
$15.00
$100.00
$5.00
$15.00
$100.00
$5.00
$15.00
$100.00

Or enter a custom amount

$

Your contribution is appreciated.

Your contribution is appreciated.

Your contribution is appreciated.

Buy Me a CoffeeBuy Me a CoffeeBuy Me a Coffee

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s