×


Python sorted() Function

The sorted() function in Python is used to sort the elements of an object in ascending or descending order and print out a sorted list. This is an available function in Python and is very useful for reordering lists. 

Here at Ibmi Media, as part of our Server Management Services, we regularly help our Customers to perform related Python function queries.

In this context, we shall look into how to use the sorted() function in Python.


What is the Python sorted() Function ?

This function specifies an iterable object for the sorted() function to reorder. The list can be sorted ascending or descending as you like. Strings are sorted alphabetically, numbers are ordered.


Python sorted() Function syntax

It's syntax is given below:

sorted(iterable, key, reverse)

The Parameter Values is explained below:

  • iterable: Required. Specify the object to sort.
  • key: Optional. Default is None.
  • reverse: Optional. Is a boolean. If False, ascending, If True, descending. The default value is False.


Examples of using Python sorted() Function

Let us see the below function:

list = ("f", "e", "d", "c", "k", "g", "h")
x = sorted(list)
print(x)

Its Output will be:

[‘c’, ‘d’, ‘e’, ‘f’, ‘g’, ‘h’, ‘k’]


Another example is given below:

1. Sort numeric:

a = (5, 9, 1, 7)
x = sorted(a)
print(x)

Its output is:

[1, 5, 7, 9]


2. Sort ascending:

a = ("b", "d", "a", "c")
x = sorted(a)
print(x)

Its Output will be:

[‘a’, ‘b’, ‘c’, ‘d’]


3. Sort descending:

a = ("b", "d", "a", "c")
x = sorted(a, reverse=True)
print(x)

Its output is:

[‘d’, ‘c’, ‘b’, ‘a’]


[Need assistance in fixing Python problems ? We can help you. ]


Conclusion

This article covers how to use the sorted() function in Python through examples. In fact, The sorted() function returns a sorted list of the specified iterable object. You can specify ascending or descending order. Strings are sorted alphabetically, and numbers are sorted numerically.


Parameters for python sorted function Syntax is given below:

Sorted(iterable, key, reverse)


Is a Python dictionary sorted?

Yes, a dictionary(collection of items in which the items are stored as key-value pairs) in Python can be sorted based on the order of item insertion. But, it was not possible in the earlier versions.