Sorting & Searching Algorithms
Learn built-in sorting with sorted() and .sort(), custom sorting with key functions, and basic searching techniques.
15 min•By Priygop Team•Updated 2026
Sorting & Searching
Sorting & Searching
# Built-in sorting
nums = [3, 1, 4, 1, 5, 9, 2, 6]
print(sorted(nums)) # returns new list
print(sorted(nums, reverse=True))
# Sort with custom key
words = ["banana", "apple", "cherry", "date"]
print(sorted(words)) # alphabetical
print(sorted(words, key=len)) # by length
print(sorted(words, key=lambda w: w[-1])) # by last char
# Sort objects
students = [("Alice", 85), ("Bob", 92), ("Charlie", 78)]
by_name = sorted(students, key=lambda s: s[0])
by_score = sorted(students, key=lambda s: s[1], reverse=True)
print(by_score) # [('Bob', 92), ('Alice', 85), ('Charlie', 78)]
# Searching
numbers = [10, 20, 30, 40, 50]
print(30 in numbers) # True (linear search)
print(numbers.index(30)) # 2
# Binary search (for sorted lists)
import bisect
sorted_nums = [1, 3, 5, 7, 9, 11]
pos = bisect.bisect_left(sorted_nums, 7)
print(f"7 is at index {pos}") # 3
# min/max with key
words = ["Python", "is", "awesome"]
longest = max(words, key=len)
print(f"Longest: {longest}")Tip
Tip
Use sorted(data, key=lambda x: x[1], reverse=True) for custom sorting. The key function extracts the comparison value.
Diagram
Loading diagram…
List for mutable sequences, tuple for immutable data, set for unique items
Common Mistake
Warning
.index() raises ValueError if item not found. Check with 'in' first: if item in list: idx = list.index(item).
Practice Task
Note
(1) Sort a list of tuples by the second element. (2) Use bisect for binary search. (3) Find the longest word using max(key=len).