How to Sort a List in Python (Ascending & Descending)
Learn how to sort a list in Python using the sort() method and the sorted() function. Discover custom key sorting and reverse order examples.
Explanation
Sorting data is one of the most common tasks in programming, whether you are ordering user profiles by age, listing products by price, or organizing search results. Python offers two built-in, highly optimized ways to sort lists: the `list.sort()` method and the `sorted()` function. Both use a highly efficient sorting algorithm called Timsort, which runs in O(N log N) time complexity.
The key difference between the two is mutability. The `list.sort()` method sorts the list in-place, meaning it directly modifies the original list and returns `None`. The `sorted()` function, on the other hand, leaves the original list unchanged and returns a brand-new sorted list. This distinction is crucial: use `sort()` when you want to save memory and don't need the original order, and use `sorted()` when you need to keep the original list intact or when sorting non-list iterables like tuples or dictionaries.
Both sorting methods accept two optional keyword arguments: `reverse` and `key`. The `reverse` argument is a boolean value; setting it to `True` sorts the list in descending (reverse) order. The `key` argument accepts a function that is applied to each element before comparison. This allows for complex sorting logic, such as sorting a list of strings by their length, or sorting a list of dictionaries by a specific key.
Step-by-Step Implementation
- 1
Use the sorted() function to sort a copy of the list without changing the original data.
- 2
Use the .sort() method directly on the list object to modify it in-place and save memory.
- 3
Pass reverse=True as a parameter to sort the items in descending order.
- 4
Use key=lambda x: ... to sort elements based on a custom property (like length or nested values).
Code Example
This code demonstrates sorting a list of numbers using both sort() and sorted(), sorting in reverse, and custom key sorting by string length.
numbers = [42, 7, 12, 89, 23]
# 1. Using sorted() (returns new list)
new_sorted = sorted(numbers)
print("Original:", numbers)
print("Sorted new list:", new_sorted)
# 2. Using sort() (in-place modification)
numbers.sort()
print("Modified original list:", numbers)
# 3. Sorting in reverse (descending)
numbers.sort(reverse=True)
print("Reverse sorted list:", numbers)
# 4. Custom sorting (by string length)
words = ["banana", "pear", "apple", "fig"]
words.sort(key=len)
print("Sorted by length:", words)Original: [42, 7, 12, 89, 23]
Sorted new list: [7, 12, 23, 42, 89]
Modified original list: [7, 12, 23, 42, 89]
Reverse sorted list: [89, 42, 23, 12, 7]
Sorted by length: ['fig', 'pear', 'apple', 'banana']Frequently Asked Questions
What is the difference between list.sort() and sorted()?
list.sort() modifies the list in-place and returns None, while sorted() leaves the original list unchanged and returns a new sorted list.
How do you sort a list of dictionaries by a key?
Use the key parameter with a lambda function or operator.itemgetter. For example: list.sort(key=lambda item: item["age"]).
Related How-To Guides
Recommended Python Resources
Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.
Python Variables & Data Types Explained
Understand Python variables and core data types (strings, integers, floats, booleans). A complete beginner guide to memory assignment in Python.
Python List Methods
Quick reference guide for Python list operations. Master appending, inserting, removing, sorting, and slicing elements.
Python vs JavaScript: Which Programming Language is Best?
A comprehensive comparison between Python and JavaScript. Explore syntax differences, performance, use cases (backend vs frontend), and coding examples.