Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on. You've got this! 🚀
Sorting & Searching Algorithms
Learn built-in sorting with sorted() and .sort(), custom sorting with key functions, and basic searching techniques.
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.
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).