Python Basics
Python Sorting
1. Two Ways to Sort
list.sort() |
sorted() |
|
|---|---|---|
| Modifies original | ✅ Yes (in place) | ❌ No |
| Returns | None |
New sorted list |
| Works on | Lists only | Any iterable |
2. .sort() — Sort In Place
Modifies the list directly. Returns None.
lst = [2, 1, 3, 4, 2, 3, 2, 1]
lst.sort()
print(lst) # → [1, 1, 2, 2, 2, 3, 3, 4]
# ❌ Don't do this — it prints None, not the sorted list
print(lst.sort()) # → None
3. sorted() — Returns a New Sorted List
Does not change the original. Always returns a list.
lst = [2, 1, 3, 4, 2, 3, 2, 1]
new_lst = sorted(lst)
print(new_lst) # → [1, 1, 2, 2, 2, 3, 3, 4]
print(lst) # → [2, 1, 3, 4, 2, 3, 2, 1] (unchanged)
4. Descending Order — reverse=True
Works with both .sort() and sorted().
lst.sort(reverse=True) # in place, descending
sorted(lst, reverse=True) # new list, descending
lst = [2, 1, 3, 4]
lst.sort(reverse=True)
print(lst) # → [4, 3, 2, 1]
5. Sorting Tuples
Tuples don't have a .sort() method (they're immutable). Use sorted() instead — it returns a list.
tup = (3, 1, 2)
sorted(tup) # → [1, 2, 3] ← returns a list!
tuple(sorted(tup)) # → (1, 2, 3) ← convert back to tuple
6. Custom Sort with key=
Pass a function to key= to sort by a custom value. The function receives each item and returns what to sort by.
lst = [[1, 2], [3, -6], [5, -4], [-1, 0], [-1, -2]]
# Sort by the second element of each inner list
def sort_second(item):
return item[1]
lst.sort(key=sort_second)
⚠️ Pass the function name only — do not call it with
().
lst.sort(key=sort_second) # ✅ correct
lst.sort(key=sort_second()) # ❌ wrong — this calls the function immediately
Sort by sum of inner list
def sort_by_sum(item):
return sum(item)
lst.sort(key=sort_by_sum)
key= also works with sorted()
new_lst = sorted(lst, key=sort_second)
new_lst = sorted(lst, key=sort_second, reverse=True)
Cheat Sheet
lst = [3, 1, 4, 1, 5, 9]
# Sort in place (ascending)
lst.sort()
# Sort in place (descending)
lst.sort(reverse=True)
# Return new sorted list (ascending)
sorted(lst)
# Return new sorted list (descending)
sorted(lst, reverse=True)
# Sort tuple (returns list)
sorted((3, 1, 2)) # → [1, 2, 3]
tuple(sorted((3, 1, 2))) # → (1, 2, 3)
# Custom sort with key
def my_key(item):
return item[1] # sort by second element
lst.sort(key=my_key)
sorted(lst, key=my_key, reverse=True)