Python’s sorted() Function

In Python, the sorted() function is a versatile tool for sorting sequences efficiently. This article aims to elucidate its usage, applications, and significance through comprehensive examples.

Understanding sorted() Function

The sorted() function in Python is utilized to sort sequences such as lists, tuples, or strings. Its syntax is as follows:

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

Here, iterable represents the sequence to be sorted, key denotes a function to be applied to each element for sorting (optional), and reverse indicates whether to sort in descending order (default is ascending).

Example 1: Sorting a List

my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]
sorted_list = sorted(my_list)
print("Sorted List:", sorted_list)

Output 1:

Sorted List: [1, 1, 2, 3, 3, 4, 5, 5, 6, 9]

Example 2: Sorting a String

my_string = "python"
sorted_string = sorted(my_string)
print("Sorted String:", ''.join(sorted_string))

Output 2:

Sorted String: hnopty

Example 3: Sorting with Custom Key Function

my_list = ['apple', 'banana', 'orange', 'grape']
sorted_list = sorted(my_list, key=len)
print("Sorted List by Length:", sorted_list)

Output 3:

Sorted List by Length: ['apple', 'grape', 'banana', 'orange']

Example 4: Sorting in Reverse Order

my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]
sorted_list_reverse = sorted(my_list, reverse=True)
print("Sorted List (Reverse):", sorted_list_reverse)

Output 4:

Sorted List (Reverse): [9, 6, 5, 5, 4, 3, 3, 2, 1, 1]

Points to Remember

  • The sorted() function sorts sequences in ascending order by default.
  • It accepts optional parameters such as key for custom sorting and reverse for sorting in descending order.
  • sorted() returns a new sorted list, leaving the original sequence unchanged.
Author: user