Mojo module
iter
Provides traits and utilities for iteration.
This module defines the core iteration protocol for Mojo through the Iterable
and Iterator
traits. Types that conform to these traits can be used with
for
loops and iteration utilities like enumerate()
, zip()
, and map()
.
The iteration protocol consists of two key traits:
Iterable
: Types that can be converted into an iteratorIterator
: Types that can produce a sequence of values
Examples:
from iter import enumerate, zip, map
# Enumerate with index
var items = ["a", "b", "c"]
for index, value in enumerate(items):
print(index, value)
# Zip multiple iterables
var numbers = [1, 2, 3]
var letters = ["x", "y", "z"]
for num, letter in zip(numbers, letters):
print(num, letter)
# Map a function over an iterable
fn square(x: Int) -> Int:
return x * x
var values = [1, 2, 3, 4]
for squared in map[square](values):
print(squared)
Traits
-
Iterable
: TheIterable
trait describes a type that can be turned into an iterator. -
Iterator
: TheIterator
trait describes a type that can be used as an iterator, e.g. in afor
loop.
Functions
-
enumerate
: Returns an iterator that yields tuples of the index and the element of the original iterator. -
iter
: Constructs an iterator from an iterable. -
map
: Returns an iterator that appliesfunction
to each element of the input iterable. -
next
: Advances the iterator and returns the next element. -
zip
: Returns an iterator that yields tuples of the elements of the original iterables.
Was this page helpful?
Thank you! We'll create more content like this.
Thank you for helping us improve!