How do I sort collections in Python using sort() and sorted()?

· Category: Python Programming

Short answer

Use .sort() to sort a list in place and sorted() to return a new sorted list from any iterable. Both accept a key function and a reverse boolean.

Steps

  1. For in-place sorting: my_list.sort(key=lambda x: x.lower(), reverse=True).
  2. For a new sorted list: new_list = sorted(my_list, key=len).
  3. Use operator.itemgetter or attrgetter for better performance with simple key extraction.
words = ["banana", "Pie", "apple", "cherry"]

# In place
words.sort(key=str.lower)
print(words)

# New list
numbers = [3, 1, 4, 1, 5]
print(sorted(numbers, reverse=True))

Tips

  • Python's sort is Timsort, a stable O(n log n) algorithm.
  • Stability means that items with equal keys retain their original order.
  • Sort complex objects by multiple fields by returning a tuple from the key function.
from operator import itemgetter

users = [
    {"name": "Alice", "age": 30},
    {"name": "Bob", "age": 25},
    {"name": "Alice", "age": 25},
]
users.sort(key=itemgetter("age", "name"))
print(users)

Common issues

  • .sort() returns None; do not assign its result to a variable.
  • Sorting a list of dicts without a key raises a TypeError because dicts are not orderable by default.
  • The key function is called once per element, so expensive computations should be cached if possible.