When a list’s values are out of order, sorting puts them in the order Python compares them. Python’s list.sort() changes the list itself, while sorted() returns a new sorted list and leaves the source unchanged.

I’ll show how to sort values in either direction and when to use sorted() to preserve the source list.

TL;DR

Use list.sort() to change a list in place, or sorted() to make a new sorted list while preserving the original.

  • Both sort ascending by default.
  • Pass reverse=True for descending order.
  • Pass key=callable to sort by a derived value.

What Does Sorting a Python List Do?

Sorting arranges list values according to their natural comparison order or a key you choose. Python offers list.sort(), which changes a list, and sorted(), which builds a new list from any iterable.

I ran sorted() on [5, 2, 4] and got [2, 4, 5]. The source stayed [5, 2, 4], so use sorted() when later code needs its original order.

Sort order, a custom key, and an unchanged original list

How to Sort a Python List Step by Step

Start with the list you want to order, then choose an in-place sort or a sorted copy based on whether the original order must remain available.

Step 1: Sort values in ascending or descending order

Call sort() with no arguments for ascending order. Set reverse=True for descending order. The sort uses that direction while comparing values, rather than reversing an already sorted list.

numbers = [8, 3, 1, 6, 2]
numbers.sort()
print("Ascending:", numbers)
numbers.sort(reverse=True)
print("Descending:", numbers)

Captured output from the named demo:

Ascending: [1, 2, 3, 6, 8]
Descending: [8, 6, 3, 2, 1]

Each call changes numbers. Use sorted(numbers, reverse=True) for a separate descending result.

Step 2: Sort strings without considering case

Pass str.casefold as key to compare text without case distinctions while retaining spelling.

words = ["pear", "Apple", "banana", "apricot"]
words.sort(key=str.casefold)
print("Case-insensitive:", words)

Output: Case-insensitive: [‘Apple’, ‘apricot’, ‘banana’, ‘pear’]. For locale-specific ordering, use locale.strxfrm instead.

Step 3: Sort records by one or more fields

The key callable receives one item and returns the value used for comparisons. A tuple key compares fields from left to right, so age sorts first and name breaks equal-age ties.

students = [("Mira", 24), ("Asha", 21), ("Dev", 21)]
students.sort(key=lambda student: (student[1], student[0]))
print("By age, then name:", students)

The captured result is [(‘Asha’, 21), (‘Dev’, 21), (‘Mira’, 24)]. For tuples, dictionaries or objects with named attributes, use operator.itemgetter or operator.attrgetter when that makes the selected field clearer. The Python list of tuples guide covers tuple data in more detail.

Edge Cases When Sorting Python Lists

Use the table to match each input or return-value issue with a concrete fix.

Case Symptom Fix
Assigning list.sort() The variable becomes None because sort() mutates the list. Call values.sort() on its own, or assign sorted(values).
Equal key values Tied records need a secondary order. Sorting is stable. Add a tuple key when a specific tie-breaker is needed.
Integers mixed with strings Direct comparison raises TypeError. Convert values to a shared comparable type with a key.
Digit strings like “2” and “10” Text order places “10” before “2”. Use key=int when every value is a digit string.

The signatures are list.sort(*, key=None, reverse=False) and sorted(iterable, /, *, key=None, reverse=False). Both key and reverse are keyword-only arguments.

For example, values.sort(key=len, reverse=True) orders strings by length. Every key result must be comparable with the others.

  • Choose heapq.nsmallest() or heapq.nlargest() when only a few extremes from a large iterable are needed.
  • Use the official Python Sorting HOWTO for stable sorting and key functions.

Conclusion

Choose the method that fits whether the source list can change. Add reverse or key only when the required order calls for them. See the official Python Sorting HOWTO and the Python list guide.

FAQ

These answers cover common variations on sorting Python lists.

How do I sort a Python list in descending order?

Call list.sort(reverse=True) to sort the list in place, or sorted(values, reverse=True) to return a new list.

How can I sort a list alphabetically without case differences?

Pass key=str.casefold, such as words.sort(key=str.casefold), to compare strings without case distinctions.

Does list.sort() return the sorted list?

No. list.sort() changes the existing list and returns None. Use sorted(values) to create and receive a new sorted list.

Share.
Leave A Reply