ZetCode

Julia Iterators Tutorial

last modified November 18, 2026

An iterator is any object that can produce a sequence of values one at a time. The for loop consumes iterators, but Julia also provides a small toolbox for building, combining, and transforming them. This tutorial covers the iterate protocol, generator expressions, collect, enumerate, zip, and the helpers in the Iterators module.

Most of these tools are lazy: they compute a value only when it is asked for, so they can work with very large or even infinite sequences without storing them. The examples were verified with Julia 1.13.4.

The iterate Protocol

Julia defines iteration through two methods of iterate. The first call returns the initial value together with a state, an internal marker that remembers where we are; each later call takes that state and returns the next value and the next state. When iterate returns nothing, the sequence is finished.

main.jl
struct Countdown
    start::Int
end

Base.iterate(c::Countdown) = (c.start, c.start - 1)
Base.iterate(c::Countdown, state) = state < 1 ? nothing : (state, state - 1)

for x in Countdown(3)
    println(x)
end

The Countdown type holds a starting number. The two Base.iterate methods supply the protocol: the first starts at start, and the second continues while the state is at least one. A for loop calls them repeatedly until it receives nothing. Defining these two methods is enough to make any type work with for, collect, and the functions below.

$ julia main.jl
3
2
1

Collecting an Iterator

A range such as 1:5 is an iterator: it produces values on demand and does not allocate an array. The collect function consumes an iterator and stores all of its values in a real collection.

main.jl
r = 1:5
a = collect(r)
println(a)
println(typeof(a))

The range r stays a UnitRange, while collect(r) creates a Vector{Int64}. The typeof function reports a value's concrete type. Collecting is useful when we need indexing, repeated passes, or an array for another function, but it gives up the memory savings of laziness.

$ julia main.jl
[1, 2, 3, 4, 5]
Vector{Int64}

Generator Expressions

A generator expression has the same shape as an array comprehension except that it uses parentheses instead of brackets. It describes how to compute values without building an array, so it can be passed directly to a reducing function such as sum.

main.jl
println(collect(i^2 for i in 1:5))
println(sum(i^2 for i in 1:5))
println(collect((i, j) for i in 1:2 for j in 1:2))

The first line collects the squares into a vector. The second sums the very same sequence without ever storing it — a reduction, meaning an operation that combines many values into one. The third generator has two nested loops and produces tuples; the later loop is the inner one, so j changes fastest.

$ julia main.jl
[1, 4, 9, 16, 25]
55
[(1, 1), (1, 2), (2, 1), (2, 2)]

enumerate

The enumerate function pairs each element with its position, starting at one. It is handy when a loop needs both the index and the value instead of only one of them.

main.jl
fruits = ["apple", "banana", "cherry"]
for (i, fruit) in enumerate(fruits)
    println("$i: $fruit")
end

Each item yielded by enumerate is a two-element tuple of the form (index, value). The parentheses in the loop variable destructure that tuple into the two names i and fruit. Applying collect would produce a vector of such tuples rather than printing them.

$ julia main.jl
1: apple
2: banana
3: cherry

zip

The zip function walks several iterators at once, yielding one tuple per step. This avoids manually indexing parallel arrays.

main.jl
names = ["Alice", "Bob", "Carol"]
scores = [88, 95, 79]
for (name, score) in zip(names, scores)
    println("$name scored $score")
end

The tuples contain one value from each input, in the order the inputs were given. As the collected form below shows, zip stops as soon as the shortest input is exhausted; extra values in longer inputs are silently ignored.

$ julia main.jl
Alice scored 88
Bob scored 95
Carol scored 79

Iterators.flatten

Sometimes an iterator yields other iterators, for example a vector of vectors. The Iterators.flatten function turns such a nested sequence into a single flat stream of values.

main.jl
nested = [[1, 2], [3, 4], [5]]
println(join(Iterators.flatten(nested), ", "))
println(collect(Iterators.flatten(nested)))

The inner arrays are visited in order and their contents are concatenated. The join function writes the values separated by a comma and a space; the second line shows that the flattened values can also be collected into a new one-dimensional vector.

$ julia main.jl
1, 2, 3, 4, 5
[1, 2, 3, 4, 5]

Iterators.product

The Iterators.product function iterates over the Cartesian product of its inputs: every value from the first iterator is paired with every value from the second, and so on for further inputs.

main.jl
for (x, y) in Iterators.product(1:2, [:a, :b])
    println((x, y))
end

Julia iterates in column-major order, so the first input varies fastest: the pairs are (1, :a), (2, :a), then (1, :b) and (2, :b). This order matches how Julia arrays store their elements. A nested for loop written with a generator expression gives the opposite order.

$ julia main.jl
(1, :a)
(2, :a)
(1, :b)
(2, :b)

Iterators.partition

The Iterators.partition function splits a sequence into consecutive chunks of a given size. Each chunk is itself an iterator that can be printed or collected.

main.jl
data = collect(1:7)
for chunk in Iterators.partition(data, 3)
    println(chunk)
end

Seven elements split into groups of three produce two full groups and one shorter final group containing only 7. Partitioning is lazy, so the chunks are produced as the loop asks for them; it is a common way to process a stream in fixed-size batches.

$ julia main.jl
[1, 2, 3]
[4, 5, 6]
[7]

Taking, Dropping and Filtering

Several helpers create a new iterator from part of an existing one. take keeps only the first n values, drop skips the first n, and filter keeps only the values for which a predicate returns true.

main.jl
println(collect(Iterators.take(1:10, 3)))
println(collect(Iterators.drop(1:10, 7)))
println(collect(Iterators.filter(isodd, 1:8)))

A predicate is a function that answers a yes/no question; isodd answers whether a number is odd. Each helper returns a new lazy iterator, so collect is needed to see the resulting values as arrays. Chaining these helpers is cheap because no intermediate arrays are created.

$ julia main.jl
[1, 2, 3]
[8, 9, 10]
[1, 3, 5, 7]

Iterators.map

The Iterators.map function applies a function to every value as it is requested. It is the lazy counterpart of map, which builds an entire result array immediately.

main.jl
mapped = Iterators.map(x -> x * 2, 1:4)
println(collect(mapped))

The arrow function x -> x * 2 is a short anonymous function: it takes x and returns twice its value. Because mapped is lazy, the multiplication happens while collect consumes the iterator, not when mapped is created.

$ julia main.jl
[2, 4, 6, 8]

Source

Julia Iterators documentation

Julia Interfaces and Iteration documentation

In this article we have worked with iterators in Julia: the iterate protocol, generator expressions, collect, enumerate, zip, and the Iterators helpers. Arrays are covered in Julia arrays, functions in Julia functions, and custom interfaces in Julia interfaces.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Julia tutorials.