Python Sorted Function
What does sorted() do?
The sorted()
function returns a new sorted list from the items in any iterable (list, tuple, string, etc.), leaving the original iterable unchanged.
Basic Syntax
sorted(iterable, key=None, reverse=False)
iterable
: The sequence to sort.key
: (Optional) A function to customize sorting (e.g., sort by length).reverse
: (Optional) If True, sorts in descending order.
Sorting different iterable types
numbers = [3, 1, 4, 2]
print(sorted(numbers)) # Output: [1, 2, 3, 4]
text = "python"
print(sorted(text)) # Output: ['h', 'n', 'o', 'p', 't', 'y']
Using the key parameter for custom sorting
words = ["apple", "banana", "cherry"]
print(sorted(words, key=len)) # Output: ['apple', 'banana', 'cherry']
print(sorted(words, key=lambda w: w[-1])) # Sort by last letter
Using the reverse parameter
numbers = [3, 1, 4, 2]
print(sorted(numbers, reverse=True)) # Output: [4, 3, 2, 1]
Difference between sorted() and list.sort()
sorted()
works on any iterable and returns a new list.list.sort()
is a method that sorts a list in place and returns None.
Summary
sorted()
returns a new sorted list from any iterable.- Original data is not changed.
- Use
key
for custom sorting andreverse
for descending order. - Works with numbers, strings, and more.