Skip to content

Archive

Iterators

20 articles
Go 13 Sep 2026 4 min read

Partition Go Slices Lazily with slices.Chunk

Batching a slice often starts as index arithmetic: advance by a fixed width, clamp the final boundary, and pass each sub-slice onward. Go 1.23 added slices.Chunk, which expresses that operation as an iterator while preserving the backing storage of the source slice. Its behavior has one detail that matters beyond syntax: every yielded chunk has its capacity clipped to its length. A caller can modify elements through a chunk, but a plain append cannot grow that chunk into the next region of the source slice.

Go 12 Sep 2026 4 min read

Traverse Slices in Reverse with slices.Backward in Go

Reverse traversal does not require reversing a slice. Since Go 1.23, slices.Backward exposes the existing elements as an iterator that emits index-value pairs from the last element toward index zero. That distinction matters when element order must stay intact. slices.Reverse changes the slice in place, while a hand-written descending loop couples traversal to index arithmetic. slices.Backward expresses reverse iteration without changing the source. The iterator keeps original indexes The function has this signature:

Go 12 Sep 2026 5 min read

Materialize Iterator Values with slices.Collect in Go

An iter.Seq can produce values without storing them all at once. That representation is useful while values are flowing through iterator-based code, but many APIs still need an ordinary slice. Since Go 1.23, slices.Collect provides that materialization boundary directly. The function consumes a one-value sequence and returns a newly built slice containing each yielded value in sequence order. It is small API surface, but its allocation, ownership, and empty-input behavior are useful to make explicit.

Go 12 Sep 2026 4 min read

Iterate Fixed-Size Slice Groups with slices.Chunk in Go

Splitting a slice into bounded groups often starts as index arithmetic: advance by a fixed width, clamp the final boundary, and take a sub-slice. Go 1.23 puts that operation in the standard library as slices.Chunk. Chunk returns an iterator rather than a [][]T. That detail keeps grouping separate from collecting, and its capacity rule gives each yielded group a useful boundary for later append calls. Chunk produces consecutive sub-slices The signature is:

Go 11 Sep 2026 7 min read

Sort Iterator Values Stably in Go with slices.SortedStableFunc

An iterator can produce values in an order that already means something: arrival order, file order, database order, or the order established by an earlier stage of a pipeline. If you need to sort those values by one key without scrambling equal-key groups, slices.SortedStableFunc handles both steps at once. It consumes an iter.Seq, collects the yielded values into a new slice, and sorts that slice with a comparator. When the comparator returns zero, the values keep the same relative order they had in the sequence.

Go 11 Sep 2026 5 min read

Iterate Go Map Values with maps.Values

Sometimes a Go map’s keys are irrelevant to the next operation. You may need to total counters, inspect status values, or pass the values into an iterator-aware helper. A plain map range works well inside one loop, but it doesn’t give you a value sequence that can cross an API boundary. Since Go 1.23, maps.Values returns an iter.Seq over a map’s values. That lets code consume values directly and postpone slice allocation until a later operation actually needs a slice.

Go 11 Sep 2026 4 min read

Iterate Go Map Pairs with maps.All

A normal range loop is often the clearest way to walk through a Go map. The situation changes when another API expects an iterator rather than a map. Starting in Go 1.23, maps.All provides that bridge by exposing a map’s key-value pairs as an iter.Seq2. maps.All doesn’t copy the map into a slice or build a second map. It returns an iterator that can feed a range loop or another iterator-aware function. The main constraint is familiar from map iteration: pair order is unspecified.

Go 11 Sep 2026 5 min read

Iterate Go Map Keys with maps.Keys

Sometimes you need only the keys from a Go map. A plain range loop handles that case well, but an iterator becomes useful when the keys need to flow into another iterator-aware API or when a function should expose keys without first allocating a slice. Since Go 1.23, maps.Keys returns an iter.Seq over a map’s keys. You can range over it directly, stop early, or pass it to helpers such as slices.Sorted and slices.Collect.

Go 10 Sep 2026 5 min read

Sort Go Iterator Values with slices.Sorted

An iter.Seq is convenient while values are flowing through a pipeline. Sorting changes the problem: a sort needs all of those values available at once. If the next step needs an ordered slice, Go has a standard-library helper that makes that boundary explicit. Go 1.23 added slices.Sorted. It consumes an iter.Seq of ordered values, collects the values into a new slice, sorts that slice in ascending order, and returns it.

Go 10 Sep 2026 6 min read

Process Go Slices in Batches with slices.Chunk

Batching a slice sounds simple until the loop starts collecting edge cases: the final batch may be short, an empty input needs sensible behavior, and careless subslicing can leave each batch with capacity to overwrite later elements. Go 1.23 added slices.Chunk, which handles that bookkeeping and exposes the batches as an iterator. If you already have the data in a slice and want to process consecutive groups without first building a [][]T, it’s a useful small tool.

Go 10 Sep 2026 5 min read

Iterate Go Slices in Reverse with slices.Backward

Walking a slice from the end used to mean writing the index loop yourself. That works, but the loop mechanics can distract from the actual job, especially when you need both the original index and the value. Since Go 1.23, slices.Backward provides that traversal directly. It returns an iterator. The slice stays in its original order, no reversed copy is created, and the indexes you receive are the real indexes from the source slice.

Go 10 Sep 2026 6 min read

Insert Iterator Pairs into Go Maps with maps.Insert

Sometimes a Go pipeline naturally produces key-value pairs, but the destination is a map you already have. Turning those pairs into a temporary map just to merge it adds a step that doesn’t help. Go 1.23 added maps.Insert for this case. It consumes an iter.Seq2[K, V] and writes each pair into an existing map. Existing keys are overwritten, unrelated entries stay in place, and the iterator can produce values lazily.

Go 10 Sep 2026 9 min read

Build Lazy Iterators in Go with iter.Seq

A Go API that returns a slice is pleasantly simple, but a slice isn’t always the right contract. Sometimes the caller only needs the first matching value. Sometimes producing each value requires work. Sometimes the complete result could be large enough that building it up front is wasteful. Go 1.23 gives those APIs a standard alternative: iter.Seq. It represents a sequence that produces values on demand and works directly with a for range loop. The useful part isn’t just new syntax. An iter.Seq can hide a container’s representation, avoid an intermediate result slice, and stop producing values as soon as the caller stops iterating.

Go 10 Sep 2026 7 min read

Build Go Maps from Iterators with maps.Collect

An iterator is a convenient way to produce key-value pairs without deciding up front where they’ll be stored. Eventually, though, an API may need an ordinary map. Writing the collection loop yourself is straightforward, but Go 1.23 gives that boundary a standard name: maps.Collect. maps.Collect consumes an iter.Seq2, stores each yielded pair in a newly allocated map, and returns that map. It’s a small helper, but it makes ownership clear: the sequence produces data; Collect creates the destination.

Go 10 Sep 2026 6 min read

Append Iterator Values to Go Slices with slices.AppendSeq

An iterator is convenient while data is flowing through a pipeline, but sooner or later you may need those values in a slice. If you already have a destination slice, collecting the iterator separately and then appending it creates an unnecessary intermediate step. Go 1.23 added slices.AppendSeq for exactly this boundary. It consumes an iter.Seq, appends each yielded value to an existing slice, and returns the resulting slice. What slices.AppendSeq does The function has a compact signature:

Python 08 Sep 2026 8 min read

Compare Neighboring Values Lazily with itertools.pairwise

Many data-processing tasks are really questions about transitions: Did a measurement increase? How long was the gap between two events? Did a state change? Is a sequence sorted? These problems need neighboring values, not arbitrary pairs. Python 3.10 added itertools.pairwise() for exactly this pattern. It produces overlapping adjacent pairs lazily, which makes the intent clearer than manual indexing and lets the same code work with lists, generators, files, and other iterables.

Python 08 Sep 2026 9 min read

Batch Python Iterables Lazily with itertools.batched

Processing data in groups is common in Python. An application may send records to an API 100 at a time, insert rows into a database in manageable groups, or divide a stream of identifiers into work units without first loading the whole input into memory. Since Python 3.12, the standard library provides itertools.batched() for this pattern. It consumes an iterable lazily and yields tuples containing up to a requested number of items. Python 3.13 added a strict option for cases where an incomplete final batch should be treated as an error.

Python 04 Sep 2026 10 min read

Use Callable-Sentinel Iteration for Chunked Reads in Python

Reading a file in chunks is a small problem that appears in many larger tasks: hashing uploads, copying large files, parsing binary records, compressing streams, and sending data without loading everything into memory. A common solution is a while loop that reads one chunk, checks for end-of-file, processes the chunk, and repeats. That loop is correct when written carefully, but Python has another standard-library pattern that expresses the same control flow as iteration:

Python 03 Sep 2026 10 min read

Building Memory-Efficient Iterator Pipelines with Python itertools

Python programs often transform data in stages: read records, discard unwanted items, reshape values, group adjacent entries, and stop after enough output has been produced. A straightforward implementation may build a new list after every stage. That is easy to understand, but it can also allocate intermediate collections that the next stage immediately consumes. Iterator pipelines offer another model. Each stage requests values from the stage before it as needed. Python’s itertools module provides building blocks for this style, including tools for chaining inputs, taking slices from streams, computing running values, grouping consecutive records, and duplicating an iterator when two consumers genuinely need it.

Rust 02 Sep 2026 4 min read

Rust Iterator Ownership: iter, iter_mut, and into_iter

Rust iteration becomes much easier once iterator choice is connected to ownership. For a collection such as Vec<T>, the central question is whether the loop should borrow values, mutate them in place, or consume the collection. The common methods are iter(), iter_mut(), and into_iter(). Borrow with iter() iter() produces shared references: fn print_names(names: &[String]) { for name in names.iter() { println!("{name}"); } } Inside the loop, name has type &String.