Scripting

Python sorted() Function

Python sorted() Function

Introduction

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. The following article is a detailed guide on how to use the sorted() function in Python as we go through the section below.

Example

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

x = sorted(list)

print(x)

Output:

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

Definition

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.

The syntax

sorted(iterable, key, reverse)

Parameter Values:

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.

More examples

Example 1: Sort numeric

a = (5, 9, 1, 7)

x = sorted(a)

print(x)

Output:

[1, 5, 7, 9]

Example 2: Sort ascending

a = ("b", "d", "a", "c")

x = sorted(a)

print(x)

Output:

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

Example 3: Sort descending

a = ("b", "d", "a", "c")

x = sorted(a, reverse=True)

print(x)

Output:

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

Conclusion

The above article is our guide on how to use the sorted() function in Python through examples.

Thanks for reading!

Similar Posts