Python provides sorted() and sort() for arranging elements in order. Although both can produce sorted elements, they differ in their return value, effect on the original data, and the types of objects they can be used with.
sorted()
Takes an iterable such as a list, tuple, string, or set and returns a new list containing its elements in sorted order. The original iterable remains unchanged.
numbers = [5, 2, 8, 1, 4]
result = sorted(numbers)
print(result)
Output
[1, 2, 4, 5, 8]
Explanation:
- numbers stores the original elements.
- sorted(numbers) arranges the elements in ascending order.
- result stores the new sorted list.
- The original numbers list remains unchanged.
sort()
Available for lists and rearranges their elements directly in ascending or descending order. It changes the original list and returns None.
numbers = [5, 2, 8, 1, 4]
numbers.sort()
print(numbers)
Output
[1, 2, 4, 5, 8]
Explanation:
- numbers stores the elements in an unsorted order.
- numbers.sort() arranges the elements in ascending order.
- The original list is modified directly.
- sort() does not create a new list.
Key Comparison
| Feature | sorted() | sort() |
|---|---|---|
Type | Built-in function | List method |
Input | Works with any iterable | Works only with lists |
| Return Value | Returns a new sorted list | Returns None |
| Original Data | Does not modify the original iterable | Modifies the original list |
| Sorting Order | Ascending by default; reverse=True for descending | Ascending by default; reverse=True for descending |
| Parameters | key and reverse | key and reverse |