Menu Close

Python sorted() Function

In this tutorial, you will learn about the python sorted() function and also you will learn how to use the python built-in sorted function.

In previous tutorials we have seen lots of Python built-in functions along with examples.

Python sorted() function

Python sorted function is a built-in function that is used to sort the specified iterable object. sorted() function sort any sequence (list, tuple, set) and always return a list in a sorted manner, without modifying the original sequence.

You can specify ascending or descending order. Strings are sorted alphabetically, and numbers are sorted numerically.

Syntax

The syntax of sorted function in Python is:-

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

Parameters

sorted function in Python takes three parameters.

  • iterable:- Required. The sequence to sort, list, dictionary, tuple, etc.
  • key:- Optional. A Function to execute to decide the order. Default is None.
  • reverse:- Optional. A Boolean. False will sort ascending, True will sort descending. Default is False.

Note:- You cannot sort a list that contains both string values and numeric values.

Python sorted function examples

Here we have took various examples to understand python sorted function.

Example:

#Sort the list
a = [1, 3, 2, 4, 5, 6, 8, 9, 10]
b = sorted(a)

#Sort the list n ascending order
print('Sorted list is:- ', b)

#Sort the list n descending order
c = sorted(a, reverse = True)
print('Reverse sort: ', b)

#Original list
print('Original list:- ', a)

Output

Sorted list is:-  [1, 2, 3, 4, 5, 6, 8, 9, 10]
Reverse sort:  [1, 2, 3, 4, 5, 6, 8, 9, 10]
Original list:-  [1, 3, 2, 4, 5, 6, 8, 9, 10]

Sorting in Ascending order

When you want to sort in ascending order then you don’t need to mention the reverse parameter in the sorted function.

Example

a = ["h", "b", "a", "c", "f", "d", "e", "g"]
x = sorted(a, reverse = True)
print(x)

Output

['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']

Sorting in Descending order

When you want to sort in ascending order then you need to mention the reverse parameter in the sorted function.

Example:

a = ("h", "b", "a", "c", "f", "d", "e", "g")
x = sorted(a, reverse = True)
print(x)

Output

['h', 'g', 'f', 'e', 'd', 'c', 'b', 'a']

Conclusion

In this article, you have learned all about Python sorted function along with examples. Python sorted function is the best to function to sort any specified iterable in ascending order or descending order.


If you like this article, please share and keep visiting for further Python built-in functions tutorial.

Python built-in functions

For more information:- Click Here

Python oct() Function
Python pow() Function

Was this post helpful?

Related Posts

Leave a Reply