How to Use Sorted Function in Python: Syntax and Examples
Use the
sorted() function in Python to return a new sorted list from any iterable. You can sort in ascending order by default or use the reverse=True argument to sort in descending order. The key argument lets you customize sorting based on a function.Syntax
The sorted() function syntax is:
sorted(iterable, *, key=None, reverse=False)
iterable: any sequence or collection to sort (like list, tuple, string).
key: a function that extracts a comparison key from each element (optional).
reverse: if True, sorts in descending order (optional).
python
sorted(iterable, *, key=None, reverse=False)
Example
This example shows sorting a list of numbers in ascending and descending order, and sorting strings by their length using the key argument.
python
numbers = [5, 2, 9, 1] sorted_numbers = sorted(numbers) sorted_numbers_desc = sorted(numbers, reverse=True) words = ['apple', 'banana', 'cherry', 'date'] sorted_by_length = sorted(words, key=len) print('Ascending:', sorted_numbers) print('Descending:', sorted_numbers_desc) print('By length:', sorted_by_length)
Output
Ascending: [1, 2, 5, 9]
Descending: [9, 5, 2, 1]
By length: ['date', 'apple', 'banana', 'cherry']
Common Pitfalls
Common mistakes include:
- Trying to sort a list in place using
sorted()instead oflist.sort().sorted()returns a new list and does not change the original. - Not using the
keyargument correctly, which can cause unexpected order. - Forgetting that
sorted()works on any iterable, not just lists.
python
numbers = [3, 1, 4] # Wrong: expecting sorted() to change original list sorted(numbers) print(numbers) # Output: [3, 1, 4] # Right: assign sorted result or use list.sort() sorted_list = sorted(numbers) print(sorted_list) # Output: [1, 3, 4]
Output
[3, 1, 4]
[1, 3, 4]
Quick Reference
| Parameter | Description | Default |
|---|---|---|
| iterable | The sequence or collection to sort | Required |
| key | Function to extract sorting key from each element | None |
| reverse | Sort in descending order if True | False |
Key Takeaways
Use sorted() to get a new sorted list from any iterable without changing the original.
Use the key parameter to customize sorting based on a function like len or a lambda.
Set reverse=True to sort in descending order.
Remember sorted() returns a new list; use list.sort() to sort in place.
sorted() works on lists, tuples, strings, and other iterables.