mirror of
https://github.com/jbranchaud/til
synced 2026-03-04 06:58:45 +00:00
Add Iterate First N Items From Enumerable as a Python TIL
This commit is contained in:
@@ -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)
|
||||
|
||||
27
python/iterate-first-n-items-from-enumerable.md
Normal file
27
python/iterate-first-n-items-from-enumerable.md
Normal file
@@ -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.
|
||||
Reference in New Issue
Block a user