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
AnyType,
ImplicitlyDestructible,
Movable
comptime members
Element
comptime Element
Required methods
__init__
__init__(out self: _Self, *, deinit take: _Self)
Create a new instance of the value by moving the value of another.
Args:
- take (
_Self): The value to move.
Returns:
_Self
__next__
__next__(mut self: _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
bounds(self: _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
nth(var self: _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 ImplicitlyDestructible 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.