Python sorted(): Sort Any Iterable in Ascending or Descending Order

The sorted() function returns a new sorted list from an iterable (list, tuple, set, etc.) without modifying the original. It’s useful for sorting numbers, strings, and custom objects efficiently.

Example

numbers = [5, 2, 8, 1]
print(sorted(numbers))

Output:

[1, 2, 5, 8]

Returns a new sorted list without changing numbers.

Syntax

sorted(iterable, key=None, reverse=False)
  • iterable → A sequence (list, tuple, set, dictionary keys, etc.).
  • key (optional) → A function for custom sorting.
  • reverse (optional) → True for descending order (default: False).

1. Sorting a List of Numbers

nums = [10, 3, 7, 2]
print(sorted(nums))  
# Output: [2, 3, 7, 10]

Returns a new sorted list.

2. Sorting in Descending Order

print(sorted(nums, reverse=True))
# Output: [10, 7, 3, 2]

Use reverse=True for descending order.

3. Sorting Strings Alphabetically

words = ["banana", "apple", "cherry"]
print(sorted(words))  
# Output: ['apple', 'banana', 'cherry']

Sorts alphabetically (A-Z).

4. Sorting with key (Custom Sorting)

words = ["banana", "apple", "cherry"]
print(sorted(words, key=len))  
# Output: ['apple', 'banana', 'cherry']

Sorts by string length instead of alphabetically.

5. Sorting a Dictionary (By Keys or Values)

data = {"b": 2, "a": 3, "c": 1}
print(sorted(data))  
# Output: ['a', 'b', 'c']  (Sorted by keys)

To sort by values:

print(sorted(data, key=data.get))  
# Output: ['c', 'b', 'a'] (Sorted by values)

Key Notes

  • Returns a new sorted list (original remains unchanged).
  • Sorts numbers, strings, tuples, and dictionaries.
  • Supports custom sorting using key functions.
  • Use reverse=True for descending order.

By using sorted(), you can sort any iterable efficiently and flexibly, making it essential for data manipulation, organizing records, and filtering results. 🚀

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top