Python key Function Tutorial#
The key function in Python is an optional argument used in many built-in functions like sorted(), min(), max(), and bisect_left() to customize how elements are compared.
Why Use the key Function?
✅ Enables custom sorting and comparisons
✅ Improves efficiency by avoiding repeated calculations
✅ Works with sorting, searching, and grouping functions
Summary of key Function Usage#
| Function | Usage with key |
|---|---|
sorted(iterable, key=...) | Custom sorting order |
min(iterable, key=...) / max(iterable, key=...) | Find min/max based on a custom rule |
bisect_left(iterable, x, key=...) | Binary search with a transformed comparison |
itertools.groupby(iterable, key=...) | Group elements based on a key |
1️⃣ Sorting with key in sorted()#
🟢 Sorting Strings by Length
| |
🟢 Sorting by Last Character
| |
2️⃣ Using key in min() and max()#
🟢 Finding the Word with the Most Vowels
| |
3️⃣ Using key in bisect_left() for Binary Search#
🟢 Finding the Closest Value
| |
✅ Finds the leftmost index where 25 should be inserted based on the first element of the tuple.
4️⃣ Grouping Elements Using key in itertools.groupby()#
🟢 Grouping Words by Their First Letter
| |