
Built-in sorting:
numbers = [3, 1, 4, 1, 5, 9, 2, 6] numbers.sort() # in-place sorted_copy = sorted(numbers) # new list reversed_list = sorted(numbers, reverse=True)
Sorting with key:
words = ["banana", "apple", "cherry", "date"]
words.sort(key=len) # sort by length
words.sort(key=str.lower) # case-insensitive
people = [("Alice", 30), ("Bob", 25), ("Charlie", 35)]
people.sort(key=lambda p: p[1]) # sort by ageSearching:
"banana" in words # True
words.index("apple") # returns position
words.count("apple") # count occurrencesBinary search (for sorted lists):
import bisect sorted_nums = [1, 3, 5, 7, 9] position = bisect.bisect_left(sorted_nums, 5) # 2
Performance: Python's sort uses Timsort — O(n log n) worst case. The in operator is O(n) for lists, O(1) for sets and dicts.
Reference:
TaskLoco™ — The Sticky Note GOAT