From efb83050ab5148f8d0990fc1157d19cc1e674fdf Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Mon, 16 Feb 2026 13:32:35 -0600 Subject: [PATCH] Add Iterate First N Items From Enumerable as a Python TIL --- README.md | 3 ++- .../iterate-first-n-items-from-enumerable.md | 27 +++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) create mode 100644 python/iterate-first-n-items-from-enumerable.md diff --git a/README.md b/README.md index bb4c553..79ab5d5 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ working across different projects via [VisualMode](https://www.visualmode.dev/). For a steady stream of TILs, [sign up for my newsletter](https://visualmode.kit.com/newsletter). -_1737 TILs and counting..._ +_1738 TILs and counting..._ See some of the other learning resources I work on: @@ -1034,6 +1034,7 @@ If you've learned something here, support my efforts writing daily TILs by - [Break Debugger On First Line Of Program](python/break-debugger-on-first-line-of-program.md) - [Create A Dummy DataFrame In Pandas](python/create-a-dummy-dataframe-in-pandas.md) - [Dunder Methods](python/dunder-methods.md) +- [Iterate First N Items From Enumerable](python/iterate-first-n-items-from-enumerable.md) - [Override The Boolean Context Of A Class](python/override-the-boolean-context-of-a-class.md) - [Store And Access Immutable Data In A Tuple](python/store-and-access-immutable-data-in-a-tuple.md) - [Test A Function With Pytest](python/test-a-function-with-pytest.md) diff --git a/python/iterate-first-n-items-from-enumerable.md b/python/iterate-first-n-items-from-enumerable.md new file mode 100644 index 0000000..8e5d4d8 --- /dev/null +++ b/python/iterate-first-n-items-from-enumerable.md @@ -0,0 +1,27 @@ +# Iterate First N Items From Enumerable + +As I'm working through the 2nd chapter of [Build a Large Language Model (from +scratch)](https://still.visualmode.dev/blogmarks/227), I came across a code +example processing a dictionary of words. This example used a for loop to print +out each dictionary entry until an index of 50 was reached on then it did a +`break`. + +This struck me as an odd way to grab and process N items from a list. I did some +searching and found `itertools` which provides +[`islice`](https://docs.python.org/3/library/itertools.html#itertools.islice). + +```python +from itertools import islice + +# preprocess words from a file into a word list +all_words = ... # not shown here + +vocab = {token: integer for integer, token in enumerate(all_words)} +for item in islice(enumerate(vocab.items()), 50): + print(item) +``` + +The `islice` function is a better approach because the intention (to grab the +first 50 things) is encoded in the function call rather than buried in a loop +body. It also has equivalent memory efficiency to the original example because +it lazily processes the list of `vocab` items.