Using the Python sorted() Method

The Sorted() Method In Python

Introduction

In this tutorial, we are going to discuss the Python sorted() method.

Sorting in any programming language is a widely performed operation on any iterable. This sorting could be in any order, like ascending or descending. Python offers a wide range of options in doing this type of sorting operation. One of them is the sorted() method.

Now let us get into the topic and look at some examples.

Understanding the Python sorted() Method

The Python sorted() method sorts the passed iterable in ascending or descending order(as specified) and returns the values in the form of list(sorted). The syntax for using the method is given below.

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

Here,

  • Iterable can be list, tuple, or set. This iterable is sorted and returned by the method,
  • key – By default it is set to none. It determines the parameter on the basis of which the values are to be sorted,
  • reverse – It accepts boolean values i.e., true or false. If the value passed is True, the iterable is sorted in reverse or descending order. Whereas, for False or for default condition, the sorting takes place in ascending order.

Working of the sorted() Method in Python

So for different values passed as arguments, we can actually sort any iterable object in ascending, or descending order. Also on the basis of user-defined or built-in functions.

Let us see how we can use the sorted() method in Python. In various ways to sort iterable objects.

Sorting in ascending order using Python sorted()

Below code illustrates the use of the Python sorted() method to sort any iterable in ascending order(normal sorting).

#initialisation of variables
list1= [2,7,6,24,73,23,57]
tup1= ('d','c','a','b')

print(sorted(list1)) #sorted list1
print(tuple(sorted(tup1))) #sorted list is type casted to tuple

Output:

[2, 6, 7, 23, 24, 57, 73]
('a', 'b', 'c', 'd')

Here,

  • Firstly, we initialize two iterable objects. One list, and another one tuple,
  • Then we directly pass them to the sorted() method with no other arguments( by default, key is none and reverse is set to false),
  • While printing the results, note that we have type-casted the result for the case of the tuple. This was done because the Python sorted() method returns sorted iterable in the form of lists.

As we can observe from the output above, both lists and tuples were sorted in our desired way.

Sorting in descending order using Python sorted()

Now let us take a look at how we can sort using the Python sorted() method in descending or reverse manner.

#initialisation of variables
list1 = [2,7,6,24,73,23,57]
tup1 = ('d','c','a','b')

print(sorted(list1, reverse= True)) #sorted list1 in reversed order
print(tuple(sorted(tup1, reverse= True))) #reversed sorted list is type casted to tuple

Output:

[73, 57, 24, 23, 7, 6, 2]
('d', 'c', 'b', 'a')

Similar to our previous example, we initialize and pass a list and a tuple to respective sorted() methods. The only change here is that this time we set the reverse parameter for the method to True. This causes the resultant list and tuple to be sorted in a reversed manner.

Custom sorting using key in sorted()

In this section we are going to focus on the key parameter for the sorted() method. As we saw earlier, we can pass any user-defined or built-in function to the sorted() method as the key to determine on the basis of which values the sorting is to be done.

Look at the example below carefully, it sorts a list of tuples on the basis of the third (3rd) element of the corresponding list item, tuple.

#initialisation of variables
list1 = [(9,8,7), (6,5,4), (3,2,1)]

def f(list):
    return list[2]
print("Sorting o the basis of key function: ", sorted(list1, key=f))

Output:

Sorting o the basis of key function:  [(3, 2, 1), (6, 5, 4), (9, 8, 7)]

Here, f() is a user-defined function that returns the 3rd element of the passed tuple. Setting the key parameter for the sorted() method ensures that the sorting of the list, list1 takes place on the basis of the 3rd element of each tuple element.

If the key was not passed, for default none value, the sorted() would have sorted the list in terms of the 1st element of each tuple in list1.

Conclusion

So in this tutorial, we learned to sort using the Python sorted() method as well as its various uses. For better understanding we recommend practicing the codes yourself. For any questions feel free to use the comments below.

References

  • Python sorted() method – Journal Dev Post,
  • Sorting – Python Documentation.