Skip to content

Commit 44b02db

Browse files
feat: key function for built-in max() function
1 parent 10e0a8d commit 44b02db

File tree

6 files changed

+23
-0
lines changed

6 files changed

+23
-0
lines changed

ebook/chapters/standard_lib_chapters/dealing_builtins.tex

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,3 +40,18 @@ \subsection{Capture Output}
4040
In this case we save the output to \lstinline{help.txt}.
4141

4242
Last but not least we are redirecting the output to stderr.
43+
44+
45+
\subsection{max() Key Function}
46+
47+
As many other built-in functions, the \lstinline{max()} function allows you to specify a key function.
48+
This allows you to (for instance) have a list of strings of integers and select the largest number of them.
49+
Without specifying \lstinline{key}, the wrong element is being selected.
50+
51+
\lstinputlisting[caption=max\_int\_in\_list\_of\_str.py]{../standard_lib/max_int_in_list_of_str.py}
52+
53+
\begin{lstlisting}[caption=Output of max\_int\_in\_list\_of\_str.py]
54+
$ python max_int_in_list_of_str.py
55+
9
56+
222
57+
\end{lstlisting}

ebook/python-snippets.epub

4.27 KB
Binary file not shown.

ebook/python-snippets.mobi

925 Bytes
Binary file not shown.

ebook/python-snippets.pdf

1.48 KB
Binary file not shown.

standard_lib/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ A collection of useful snippets using only the standard library.
3232
| human_readable_bytecode | Print the bytecode representations in a human readble format |
3333
| keep_metadata_on_decorator_usage | Keep functions metadata after decoration |
3434
| list_unpacking | Unpacking a list using the `*` operator |
35+
| max_int_in_list_of_str | Get the largest number from a list of strings |
3536
| merge_arbitrary_number_of_dicts | The most pythonic way to merge an arbitrary number of dicts |
3637
| MicroWebServer | A lightweight micro web server |
3738
| multi_dict_with_init | Provide a multi dict with default value using `defaultdict` |
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
numbers = ["9", "44", "8", "222"]
2+
3+
max_string = max(numbers)
4+
print(f"Max string: {max_string}")
5+
6+
max_number = max(numbers, key=int)
7+
print(f"Max number: {max_number}")

0 commit comments

Comments
 (0)