For the complete Mojo documentation index, see llms.txt. Markdown versions of all pages are available by appending .md to any URL (e.g. /docs/manual/basics.md).
Iterator
The Iterator trait describes a type that can be used as an iterator, e.g. in a for loop.
Implemented traits
comptime members
Element
comptime Element
Required methods
__next__
def __next__(mut self) -> Self.Element
Returns the next element from the iterator.
Returns:
_Self.Element: The next element.
Raises:
StopIteration if there are no more elements.
Provided methods
bounds
def bounds(self) -> Tuple[Int, Optional[Int]]
Returns bounds [lower, upper] for the remaining iterator length.
This helps collections pre-allocate memory when constructed from iterators.
The default implementation returns (0, None).
Safety:
If the upper bound is not None, implementations must ensure that lower <= upper.
The bounds are hints only - iterators may not comply with them. Never omit safety
checks when using bounds to build collections.
Examples:
from std.iter import Iterator
def preallocate[I: Iterator](mut iter: I) -> List[Int]:
var lower, _upper = iter.bounds()
# Pre-allocate based on estimated iterator length
return List[Int](capacity=lower)
Returns:
Tuple[Int, Optional[Int]]: A tuple where the first element is the lower bound and the second
is an optional upper bound (None means unknown or upper > Int.MAX).
nth
def nth(var self, n: Int) -> Optional[Self.Element]
Advances the iterator by n elements (destroying them) and returns the next element, or None if the iterator is exhausted first.
Examples:
var l = [10, 20, 30, 40]
print(iter(l).nth(0).value()) # 10
print(iter(l).nth(3).value()) # 40
var missing = iter(l).nth(10) # None
Constraints:
Self.Element must conform to Deinitable so the
intermediate elements can be discarded.
Args:
- n (
Int): The 0-indexed position of the element to return. Must be non-negative.
Returns:
Optional[_Self.Element]: The element at index n, or None if the iterator has fewer than
n + 1 remaining elements.
count
def count(var self) -> Int
Consumes the iterator and returns how many elements it yielded.
Each element is advanced past and destroyed, so the iterator is
exhausted afterwards. Unlike len(), which is O(1), this walks the
whole iterator. An iterator that can compute its remaining length
cheaply can override this method.
Preconditions:
The iterator must yield at most Int.MAX elements.
Performance: O(n), where n is the number of remaining elements.
Examples:
var nums = [10, 20, 30]
print(iter(nums).count()) # 3
Constraints:
Self.Element must conform to Deinitable so the elements can
be discarded.
Returns:
Int: The number of elements the iterator yielded before it stopped.