How to Sort a List in Python: Simple Guide with Examples
To sort a list in Python, use the
list.sort() method to sort the list in place or the sorted() function to get a new sorted list. Both allow sorting in ascending order by default and can sort in descending order by setting reverse=True.Syntax
The two main ways to sort a list in Python are:
list.sort(key=None, reverse=False): Sorts the list itself and changes its order.sorted(iterable, key=None, reverse=False): Returns a new sorted list from any iterable without changing the original.
Parameters:
key: Optional function to customize sorting criteria.reverse: Optional boolean to sort in descending order ifTrue.
python
my_list.sort() sorted_list = sorted(my_list) # With options my_list.sort(reverse=True) sorted_list = sorted(my_list, key=lambda x: x*2, reverse=True)
Example
This example shows sorting a list of numbers in ascending and descending order using both list.sort() and sorted(). It also shows that sorted() returns a new list while list.sort() changes the original list.
python
numbers = [5, 2, 9, 1, 5, 6] # Sort in place (ascending) numbers.sort() print("Sorted with list.sort():", numbers) # Sort in place (descending) numbers.sort(reverse=True) print("Descending with list.sort():", numbers) # Original list numbers = [5, 2, 9, 1, 5, 6] # Get new sorted list (ascending) sorted_numbers = sorted(numbers) print("Sorted with sorted():", sorted_numbers) # Get new sorted list (descending) sorted_numbers_desc = sorted(numbers, reverse=True) print("Descending with sorted():", sorted_numbers_desc) # Original list remains unchanged print("Original list after sorted():", numbers)
Output
Sorted with list.sort(): [1, 2, 5, 5, 6, 9]
Descending with list.sort(): [9, 6, 5, 5, 2, 1]
Sorted with sorted(): [1, 2, 5, 5, 6, 9]
Descending with sorted(): [9, 6, 5, 5, 2, 1]
Original list after sorted(): [5, 2, 9, 1, 5, 6]
Common Pitfalls
Common mistakes when sorting lists include:
- Using
list.sort()expecting it to return a new list (it returnsNone). - Not realizing
list.sort()changes the original list. - Forgetting to use
reverse=Trueto sort in descending order. - Trying to sort lists with mixed data types that cannot be compared.
python
my_list = [3, 1, 2] # Wrong: expecting a new sorted list sorted_list = my_list.sort() print(sorted_list) # Prints None # Right: use sorted() to get new list sorted_list = sorted(my_list) print(sorted_list) # Prints [1, 2, 3]
Output
None
[1, 2, 3]
Quick Reference
| Method | Description | Modifies Original? | Returns |
|---|---|---|---|
| list.sort() | Sorts the list in place | Yes | None |
| sorted(iterable) | Returns a new sorted list | No | New sorted list |
Key Takeaways
Use list.sort() to sort a list in place without creating a new list.
Use sorted() to get a new sorted list and keep the original unchanged.
Set reverse=True to sort in descending order.
list.sort() returns None, so don’t assign its result to a variable.
Sorting works best when all list items are comparable.