A list of strings, and you want the longest one. You could write a for-loop and track the winner manually — or you could let Python's built-ins do the bookkeeping. Which would you reach for?
max() accepts a list and a key function? So max(snippets, key=len) gives me the element with the biggest length, not the biggest string value alphabetically?
Exactly. max with a key is the idiomatic "biggest by this criterion" call. key=len tells max to compare on length, not on alphabetical order:
snippets = [m.get("snippet", "") for m in messages]
longest = max(snippets, key=len)What happens if the list is empty? max([]) must raise something, right?
max on an empty list raises ValueError. The safe pattern is a default argument — max(snippets, key=len, default="") returns the default without raising:
def longest_snippet(max_results: int) -> str:
result = toolset.execute_action(Action.GMAIL_FETCH_EMAILS, {"max_results": max_results})
snippets = [m.get("snippet", "") for m in result.get("messages", [])]
return max(snippets, key=len, default="")Could I use sorted(snippets, key=len, reverse=True)[0] instead? Same result?
Same winner, but sorted is O(n log n) and builds a new list. max is O(n) and returns only the winner. When you need the top one, max is cheaper. When you need the top three, sorted(..., reverse=True)[:3] is the right tool.
So every selection problem is the same skeleton — fetch, comprehend to a list, use max or sorted to pick?
Fetch, extract, select. The key function swaps to rank on whatever you care about — length, timestamp, a count, a score. Different criterion, same three-step shape.
TL;DR: max(items, key=fn, default=x) is the one-line idiomatic winner picker.
key=len ranks by lengthdefault="" kills the empty-list ValueErrorsorted(..., reverse=True)[0]| Need | Use |
|---|---|
| Single top item | max(xs, key=fn) |
| Top N items | sorted(xs, key=fn, reverse=True)[:N] |
| Ordered full list | sorted(xs, key=fn) |
max returns one element. sorted rebuilds the list. Pick the one that matches the shape of your answer.
A list of strings, and you want the longest one. You could write a for-loop and track the winner manually — or you could let Python's built-ins do the bookkeeping. Which would you reach for?
max() accepts a list and a key function? So max(snippets, key=len) gives me the element with the biggest length, not the biggest string value alphabetically?
Exactly. max with a key is the idiomatic "biggest by this criterion" call. key=len tells max to compare on length, not on alphabetical order:
snippets = [m.get("snippet", "") for m in messages]
longest = max(snippets, key=len)What happens if the list is empty? max([]) must raise something, right?
max on an empty list raises ValueError. The safe pattern is a default argument — max(snippets, key=len, default="") returns the default without raising:
def longest_snippet(max_results: int) -> str:
result = toolset.execute_action(Action.GMAIL_FETCH_EMAILS, {"max_results": max_results})
snippets = [m.get("snippet", "") for m in result.get("messages", [])]
return max(snippets, key=len, default="")Could I use sorted(snippets, key=len, reverse=True)[0] instead? Same result?
Same winner, but sorted is O(n log n) and builds a new list. max is O(n) and returns only the winner. When you need the top one, max is cheaper. When you need the top three, sorted(..., reverse=True)[:3] is the right tool.
So every selection problem is the same skeleton — fetch, comprehend to a list, use max or sorted to pick?
Fetch, extract, select. The key function swaps to rank on whatever you care about — length, timestamp, a count, a score. Different criterion, same three-step shape.
TL;DR: max(items, key=fn, default=x) is the one-line idiomatic winner picker.
key=len ranks by lengthdefault="" kills the empty-list ValueErrorsorted(..., reverse=True)[0]| Need | Use |
|---|---|
| Single top item | max(xs, key=fn) |
| Top N items | sorted(xs, key=fn, reverse=True)[:N] |
| Ordered full list | sorted(xs, key=fn) |
max returns one element. sorted rebuilds the list. Pick the one that matches the shape of your answer.
Create a free account to get started. Paid plans unlock all tracks.