Python Key Function

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

FunctionUsage 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

words = ["apple", "banana", "grape", "kiwi"]
sorted_words = sorted(words, key=len)

print(sorted_words)
# Output: ['kiwi', 'apple', 'grape', 'banana']

🟢 Sorting by Last Character

words = ["apple", "banana", "grape", "kiwi"]
sorted_by_last = sorted(words, key=lambda x: x[-1])

print(sorted_by_last)
# Output: ['banana', 'apple', 'grape', 'kiwi']

2️⃣ Using key in min() and max()

🟢 Finding the Word with the Most Vowels

def count_vowels(word):
    return sum(1 for c in word if c in "aeiou")

words = ["apple", "banana", "grape", "peach"]
max_word = max(words, key=count_vowels)

print(max_word)
# Output: 'banana'

3️⃣ Using key in bisect_left() for Binary Search

🟢 Finding the Closest Value

import bisect

arr = [(10, "A"), (20, "B"), (30, "C")]

# Searching for value 25 based on the first element of the tuple
index = bisect.bisect_left(arr, 25, key=lambda x: x[0])

print(index)
# Output: 2

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

from itertools import groupby

words = ["apple", "banana", "apricot", "blueberry", "cherry"]
words.sort()  # `groupby()` requires sorted data

grouped = {k: list(g) for k, g in groupby(words, key=lambda x: x[0])}
print(grouped)

# output
# {'a': ['apple', 'apricot'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}

發佈留言