Sorting is the operation that brings order to your data. A sorted list is easier for humans to scan, required for binary search algorithms, and often the expected output format when presenting data to users. Python gives you two paths to a sorted list: the sort method, which rearranges a list in place, and the sorted built-in function, which returns a new sorted list and leaves the original untouched. Both support custom sort criteria through a key parameter and descending order through a reverse flag, and both use the Timsort algorithm, which is stable, efficient on partially ordered data, and among the fastest general-purpose sorting implementations available in any language.
Reversing is simpler than sorting but equally useful. The reverse method flips the order of items in place, and a slice with a step of -1 creates a reversed copy. This article covers both sorting and reversing, starting with basic ascending sorts and progressing through custom keys, descending order, multi-pass sorting, and reverse techniques. Before sorting a list, you need to have items in it; see creating and accessing Python lists and modifying Python lists if you need to populate a list first.
Basic sorting with sort and sorted
The simplest sort is an ascending sort on a list of comparable items. Call the sort method on the list, and Python rearranges its elements from smallest to largest using the less-than operator for comparisons. Numbers sort by numeric value, and strings sort by Unicode code point order.
nums = [4, 1, 7, 3, 9]
nums.sort()After this call, the list is ordered from 1 to 9. The original order is gone because the sort method modifies the list in place. The sorted function gives you the same result without destroying the original list. Pass it any iterable, and it returns a new list with the items in ascending order. Now your original list is still unsorted and the result holds the sorted values. Use sorted when you need to preserve the unsorted data for later use, or when you are sorting something that is not a list, like a tuple, a set, or the keys of a dictionary.
Controlling sort direction with the reverse parameter
Both the sort method and the sorted function accept a reverse parameter. Setting reverse to True produces a descending sort, from largest to smallest. The default is False, which produces ascending order. The parameter is a keyword-only argument, so you must spell it with the equals sign; you cannot pass a positional True or False.
scores = [65, 92, 78, 88, 73]
scores.sort(reverse=True)The list becomes ordered from highest to lowest. The reverse parameter is separate from the reverse method. The parameter controls sort direction during a sort call, while the method flips an already-sorted, or any, list end-to-end without comparing any items.
Sorting with a key function
The real power of Python's sorting comes from the key parameter. Instead of comparing items directly, Python calls the key function on each item exactly once, caches the result, and then sorts by those computed keys. This is faster than providing a comparison function because each item is transformed only once, not on every pairwise comparison.
A common use case is case-insensitive string sorting. By default, uppercase letters sort before lowercase letters because their Unicode code points are smaller. Passing a case-insensitive key function normalizes each string before comparison, producing the order a human would expect.
words = ["Banana", "apple", "Cherry", "date"]
words.sort(key=str.casefold)Each string is compared by its casefolded version, but the original casing stays intact in the sorted result. The key function can be any callable that accepts one argument and returns a value Python knows how to compare. Common choices include built-in functions like len for sorting by length and abs for sorting by absolute value. You can also write a short custom function when your sorting logic needs more than a single built-in can provide.
Sorting by multiple criteria and reversing
Stability makes multi-pass sorting simple and reliable. To sort by a primary key and break ties with a secondary key, sort by the secondary key first, then by the primary key. The stable sort preserves the secondary ordering when items share the same primary key. After the second sort, the list is grouped by the primary key, and within each group items are ordered by the secondary key because the stable sort preserved that ordering from the first pass.
Reversing changes the order of items to the opposite of what it currently is. The reverse method does this in place, swapping the first item with the last, the second with the second-to-last, and so on through the middle. It does not sort the list; it simply flips the existing order. Calling reverse a second time restores the original order. The method returns None, following Python's convention for in-place mutators.
letters = ["a", "b", "c", "d"]
letters.reverse()If you need a reversed copy without changing the original, use a slice with a step of -1. This starts from the end, moves toward the beginning, and produces a new list with the reversed sequence. The original list stays unchanged. The slice approach works on any sequence type, not just lists.
Items that cannot be sorted
Not all Python objects can be compared with the less-than operator. Attempting to sort a list that mixes incompatible types, integers and strings, or numbers and None, raises a TypeError. The same error occurs when a key function returns values that cannot be compared. Before sorting, ensure that every item in the list, or every value returned by the key function, supports comparison.
The solution is to normalize the data before sorting. Convert everything to strings if you only need a display ordering, or filter and separate by type if the types carry different meanings. The article on common collection mistakes in Python covers strategies for handling heterogeneous data safely.
Rune AI
Key Insights
- The sort method modifies a list in place; the sorted function returns a new sorted list from any iterable.
- Use the reverse=True parameter to sort in descending order.
- The key parameter accepts a function that transforms each item before comparison.
- The reverse method flips the order in place; slicing with [::-1] creates a reversed copy.
- Sort stability means items with equal keys keep their original relative order.
Frequently Asked Questions
What is the difference between the sort method and the sorted function?
How do I sort a list of strings ignoring case?
Can I sort a list of dictionaries by a specific field?
Conclusion
Sorting and reversing are the two operations that control the order of your list data. Knowing both the in-place methods and the function-based alternatives, understanding the key parameter for custom sort criteria, and recognizing the difference between the reverse parameter and the reverse method gives you complete command of list ordering.
More in this topic
Nested Lists in Python
Learn how to create, access, and modify nested lists in Python. Build grids and matrices, and understand how shallow copies affect multi-dimensional data.
List Comprehensions in Python
Master Python list comprehensions to create, filter, and transform lists in a single line. Learn the syntax, common patterns, and when to use a regular loop instead.
Copy Python Lists
Learn how to copy Python lists using slicing, the copy method, the list constructor, and the copy module. Understand shallow vs deep copies.