How to Sort a List in Python
Sort a Python list two ways — in place with list.sort(), or into a new list with sorted() — and order by length, case, or a dictionary key with the key= argument.
Overview
Python gives you two ways to sort a list. list.sort() sorts the list in place and returns None. sorted() leaves the original untouched and returns a new sorted list. Both accept the same two keyword arguments — key and reverse — so once you know one, you know the other.
Steps
1. Sort in place with list.sort()
nums = [3, 1, 2]
nums.sort()
print(nums) # [1, 2, 3]
2. Get a new sorted list with sorted()
Use sorted() when you need to keep the original list. It works on any iterable and always returns a list.
src = [3, 1, 2]
result = sorted(src)
print(result) # [1, 2, 3]
print(src) # [3, 1, 2] — unchanged
3. Descending order with reverse=True
print(sorted([3, 1, 2], reverse=True)) # [3, 2, 1]
4. Custom order with key=
key takes a function applied to each element to decide the sort order. Sort by length, or case-insensitively with str.lower:
print(sorted(["bb", "a", "ccc"], key=len)) # ['a', 'bb', 'ccc']
words = ["banana", "apple", "Cherry"]
print(sorted(words)) # ['Cherry', 'apple', 'banana'] (uppercase first)
print(sorted(words, key=str.lower)) # ['apple', 'banana', 'Cherry'] (case-insensitive)
5. Sort a list of dictionaries
people = [
{"name": "Ada", "age": 36},
{"name": "Bo", "age": 22},
]
by_age = sorted(people, key=lambda p: p["age"])
print([p["name"] for p in by_age]) # ['Bo', 'Ada']
Runnable example
A complete, runnable example — open it in the Python compiler:
products = [
{"name": "Pen", "price": 3},
{"name": "Notebook", "price": 6},
{"name": "Eraser", "price": 1},
]
# Cheapest first, without changing the original list
cheapest_first = sorted(products, key=lambda p: p["price"])
for p in cheapest_first:
print(p["name"], p["price"])
# Eraser 1
# Pen 3
# Notebook 6
Common pitfalls
Like JavaScript, Python's sort is stable: elements that compare equal keep their original order, so you can sort by one key and then another to get a multi-level sort.
Frequently asked questions
What's the difference between sort() and sorted() in Python?
list.sort() sorts the list in place and returns None. sorted() returns a new sorted list and leaves the original unchanged. Both accept key and reverse.Why does my list become None after sorting?
list.sort(), which returns None. Call .sort() as a statement (nums.sort()), or use sorted(nums) if you want the sorted list as a value.How do I sort a list of dictionaries by a key?
sorted(items, key=lambda d: d['age']). Add reverse=True for descending order.How do I sort strings case-insensitively?
key=str.lower, e.g. sorted(words, key=str.lower). The default sort is case-sensitive and orders uppercase letters before lowercase ones.