Notes

`sorted()` Function in Python [ English ]

< Prev Next >

1. Introduction

The sorted() function in Python is a built-in function used to sort the elements of an iterable object such as a list, tuple, string, or dictionary. It returns a new sorted list containing all the elements of the iterable.

Unlike the sort() method of lists, the sorted() function does not modify the original object. Instead, it creates and returns a new list with the elements arranged in sorted order.

By default, sorted() arranges elements in ascending order, but it can also sort in descending order or according to a custom sorting rule.

2. Syntax

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

Parameters

  1. iterable The collection of elements to be sorted (list, tuple, string, etc.).

  2. key (optional) A function that specifies the value used for sorting.

  3. reverse (optional) If True, the elements are sorted in descending order. Default value is False, which means ascending order.

Return Value

3. Basic Example

numbers = [5, 2, 9, 1, 7]

result = sorted(numbers)

print(result)

Output

[1, 2, 5, 7, 9]

Explanation

4. Example with Descending Order

numbers = [5, 2, 9, 1, 7]

result = sorted(numbers, reverse=True)

print(result)

Output

[9, 7, 5, 2, 1]

Explanation

5. Example with a String

text = "python"

result = sorted(text)

print(result)

Output

['h', 'n', 'o', 'p', 't', 'y']

Explanation

6. Example with a Tuple

numbers = (8, 3, 6, 1)

result = sorted(numbers)

print(result)

Output

[1, 3, 6, 8]

Explanation

7. Example with key Parameter

words = ["apple", "banana", "kiwi", "cherry"]

result = sorted(words, key=len)

print(result)

Output

['kiwi', 'apple', 'banana', 'cherry']

Explanation

8. Sorting a Dictionary

data = {"b": 2, "a": 1, "c": 3}

result = sorted(data)

print(result)

Output

['a', 'b', 'c']

Explanation

9. Difference Between sorted() and list.sort()

Feature sorted() list.sort()
Works on Any iterable Only lists
Returns value Returns a new sorted list Returns None
Original data Not modified Modified

Example:

numbers = [4, 2, 8]

sorted_numbers = sorted(numbers)

print(sorted_numbers)
print(numbers)

Output:

[2, 4, 8]
[4, 2, 8]

10. Summary

< Prev Next >