Base.Iterators.Stateful
—TypeStateful(itr)
There are several different ways to think about this iterator wrapper:
Channel
-like abstraction.Stateful
provides the regular iterator interface. Like other mutable iterators (e.g.Base.Channel
), if iteration is stopped early (e.g. by abreak
in afor
loop), iteration can be resumed from the same spot by continuing to iterate over the same iterator object (in contrast, an immutable iterator would restart from the beginning).
Examples
julia> a = Iterators.Stateful("abcdef");julia> isempty(a)falsejulia> popfirst!(a)'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)julia> collect(Iterators.take(a, 3))3-element Vector{Char}: 'b': ASCII/Unicode U+0062 (category Ll: Letter, lowercase) 'c': ASCII/Unicode U+0063 (category Ll: Letter, lowercase) 'd': ASCII/Unicode U+0064 (category Ll: Letter, lowercase)julia> collect(a)2-element Vector{Char}: 'e': ASCII/Unicode U+0065 (category Ll: Letter, lowercase) 'f': ASCII/Unicode U+0066 (category Ll: Letter, lowercase)julia> Iterators.reset!(a); popfirst!(a)'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)julia> Iterators.reset!(a, "hello"); popfirst!(a)'h': ASCII/Unicode U+0068 (category Ll: Letter, lowercase)
julia> a = Iterators.Stateful([1,1,1,2,3,4]);julia> for x in a; x == 1 || break; endjulia> peek(a)3julia> sum(a) # Sum the remaining elements7
Base.Iterators.zip
—Functionzip(iters...)
Run multiple iterators at the same time, until any of them is exhausted. The value type of thezip
iterator is a tuple of values of its subiterators.
zip
orders the calls to its subiterators in such a way that stateful iterators will not advance when another iterator finishes in the current iteration.
zip()
with no arguments yields an infinite iterator of empty tuples.
See also:enumerate
,Base.splat
.
Examples
julia> a = 1:51:5julia> b = ["e","d","b","c","a"]5-element Vector{String}: "e" "d" "b" "c" "a"julia> c = zip(a,b)zip(1:5, ["e", "d", "b", "c", "a"])julia> length(c)5julia> first(c)(1, "e")
Base.Iterators.enumerate
—Functionenumerate(iter)
An iterator that yields(i, x)
wherei
is a counter starting at 1, andx
is thei
th value from the given iterator. It's useful when you need not only the valuesx
over which you are iterating, but also the number of iterations so far.
Note thati
may not be valid for indexingiter
, or may index a different element. This will happen ifiter
has indices that do not start at 1, and may happen for strings, dictionaries, etc. See thepairs(IndexLinear(), iter)
method if you want to ensure thati
is an index.
Examples
julia> a = ["a", "b", "c"];julia> for (index, value) in enumerate(a) println("$index $value") end1 a2 b3 cjulia> str = "naïve";julia> for (i, val) in enumerate(str) print("i = ", i, ", val = ", val, ", ") try @show(str[i]) catch e println(e) end endi = 1, val = n, str[i] = 'n'i = 2, val = a, str[i] = 'a'i = 3, val = ï, str[i] = 'ï'i = 4, val = v, StringIndexError("naïve", 4)i = 5, val = e, str[i] = 'v'
Base.Iterators.rest
—Functionrest(iter, state)
An iterator that yields the same elements asiter
, but starting at the givenstate
.
See also:Iterators.drop
,Iterators.peel
,Base.rest
.
Examples
julia> collect(Iterators.rest([1,2,3,4], 2))3-element Vector{Int64}: 2 3 4
Base.Iterators.countfrom
—Functioncountfrom(start=1, step=1)
An iterator that counts forever, starting atstart
and incrementing bystep
.
Examples
julia> for v in Iterators.countfrom(5, 2) v > 10 && break println(v) end579
Base.Iterators.take
—Functiontake(iter, n)
An iterator that generates at most the firstn
elements ofiter
.
See also:drop
,peel
,first
,Base.take!
.
Examples
julia> a = 1:2:111:2:11julia> collect(a)6-element Vector{Int64}: 1 3 5 7 9 11julia> collect(Iterators.take(a,3))3-element Vector{Int64}: 1 3 5
Base.Iterators.takewhile
—Functiontakewhile(pred, iter)
An iterator that generates element fromiter
as long as predicatepred
is true, afterwards, drops every element.
This function requires at least Julia 1.4.
Examples
julia> s = collect(1:5)5-element Vector{Int64}: 1 2 3 4 5julia> collect(Iterators.takewhile(<(3),s))2-element Vector{Int64}: 1 2
Base.Iterators.drop
—Functiondrop(iter, n)
An iterator that generates all but the firstn
elements ofiter
.
Examples
julia> a = 1:2:111:2:11julia> collect(a)6-element Vector{Int64}: 1 3 5 7 9 11julia> collect(Iterators.drop(a,4))2-element Vector{Int64}: 9 11
Base.Iterators.dropwhile
—Functiondropwhile(pred, iter)
An iterator that drops element fromiter
as long as predicatepred
is true, afterwards, returns every element.
This function requires at least Julia 1.4.
Examples
julia> s = collect(1:5)5-element Vector{Int64}: 1 2 3 4 5julia> collect(Iterators.dropwhile(<(3),s))3-element Vector{Int64}: 3 4 5
Base.Iterators.cycle
—Functioncycle(iter[, n::Int])
An iterator that cycles throughiter
forever. Ifn
is specified, then it cycles throughiter
that many times. Wheniter
is empty, so arecycle(iter)
andcycle(iter, n)
.
Iterators.cycle(iter, n)
is the lazy equivalent ofBase.repeat
(vector, n)
, whileIterators.repeated
(iter, n)
is the lazyBase.fill
(item, n)
.
The methodcycle(iter, n)
was added in Julia 1.11.
Examples
julia> for (i, v) in enumerate(Iterators.cycle("hello")) print(v) i > 10 && break endhellohellohjulia> foreach(print, Iterators.cycle(['j', 'u', 'l', 'i', 'a'], 3))juliajuliajuliajulia> repeat([1,2,3], 4) == collect(Iterators.cycle([1,2,3], 4))truejulia> fill([1,2,3], 4) == collect(Iterators.repeated([1,2,3], 4))true
Base.Iterators.repeated
—Functionrepeated(x[, n::Int])
An iterator that generates the valuex
forever. Ifn
is specified, generatesx
that many times (equivalent totake(repeated(x), n)
).
See alsofill
, and compareIterators.cycle
.
Examples
julia> a = Iterators.repeated([1 2], 4);julia> collect(a)4-element Vector{Matrix{Int64}}: [1 2] [1 2] [1 2] [1 2]julia> ans == fill([1 2], 4)truejulia> Iterators.cycle([1 2], 4) |> collect |> println[1, 2, 1, 2, 1, 2, 1, 2]
Base.Iterators.product
—Functionproduct(iters...)
Return an iterator over the product of several iterators. Each generated element is a tuple whosei
th element comes from thei
th argument iterator. The first iterator changes the fastest.
See also:zip
,Iterators.flatten
.
Examples
julia> collect(Iterators.product(1:2, 3:5))2×3 Matrix{Tuple{Int64, Int64}}: (1, 3) (1, 4) (1, 5) (2, 3) (2, 4) (2, 5)julia> ans == [(x,y) for x in 1:2, y in 3:5] # collects a generator involving Iterators.producttrue
Base.Iterators.flatten
—Functionflatten(iter)
Given an iterator that yields iterators, return an iterator that yields the elements of those iterators. Put differently, the elements of the argument iterator are concatenated.
Examples
julia> collect(Iterators.flatten((1:2, 8:9)))4-element Vector{Int64}: 1 2 8 9julia> [(x,y) for x in 0:1 for y in 'a':'c'] # collects generators involving Iterators.flatten6-element Vector{Tuple{Int64, Char}}: (0, 'a') (0, 'b') (0, 'c') (1, 'a') (1, 'b') (1, 'c')
Base.Iterators.flatmap
—FunctionIterators.flatmap(f, iterators...)
Equivalent toflatten(map(f, iterators...))
.
See alsoIterators.flatten
,Iterators.map
.
This function was added in Julia 1.9.
Examples
julia> Iterators.flatmap(n -> -n:2:n, 1:3) |> collect9-element Vector{Int64}: -1 1 -2 0 2 -3 -1 1 3julia> stack(n -> -n:2:n, 1:3)ERROR: DimensionMismatch: stack expects uniform slices, got axes(x) == (1:3,) while first had (1:2,)[...]julia> Iterators.flatmap(n -> (-n, 10n), 1:2) |> collect4-element Vector{Int64}: -1 10 -2 20julia> ans == vec(stack(n -> (-n, 10n), 1:2))true
Base.Iterators.partition
—Functionpartition(collection, n)
Iterate over a collectionn
elements at a time.
Examples
julia> collect(Iterators.partition([1,2,3,4,5], 2))3-element Vector{SubArray{Int64, 1, Vector{Int64}, Tuple{UnitRange{Int64}}, true}}: [1, 2] [3, 4] [5]
Base.Iterators.map
—FunctionIterators.map(f, iterators...)
Create a lazy mapping. This is another syntax for writing(f(args...) for args in zip(iterators...))
.
This function requires at least Julia 1.6.
Examples
julia> collect(Iterators.map(x -> x^2, 1:3))3-element Vector{Int64}: 1 4 9
Base.Iterators.filter
—FunctionIterators.filter(flt, itr)
Given a predicate functionflt
and an iterable objectitr
, return an iterable object which upon iteration yields the elementsx
ofitr
that satisfyflt(x)
. The order of the original iterator is preserved.
This function islazy; that is, it is guaranteed to return in$Θ(1)$ time and use$Θ(1)$ additional space, andflt
will not be called by an invocation offilter
. Calls toflt
will be made when iterating over the returned iterable object. These calls are not cached and repeated calls will be made when reiterating.
Subsequentlazy transformations on the iterator returned fromfilter
, such as those performed byIterators.reverse
orcycle
, will also delay calls toflt
until collecting or iterating over the returned iterable object. If the filter predicate is nondeterministic or its return values depend on the order of iteration over the elements ofitr
, composition with lazy transformations may result in surprising behavior. If this is undesirable, either ensure thatflt
is a pure function or collect intermediatefilter
iterators before further transformations.
SeeBase.filter
for an eager implementation of filtering for arrays.
Examples
julia> f = Iterators.filter(isodd, [1, 2, 3, 4, 5])Base.Iterators.Filter{typeof(isodd), Vector{Int64}}(isodd, [1, 2, 3, 4, 5])julia> foreach(println, f)135julia> [x for x in [1, 2, 3, 4, 5] if isodd(x)] # collects a generator over Iterators.filter3-element Vector{Int64}: 1 3 5
Base.Iterators.accumulate
—FunctionIterators.accumulate(f, itr; [init])
Given a 2-argument functionf
and an iteratoritr
, return a new iterator that successively appliesf
to the previous value and the next element ofitr
.
This is effectively a lazy version ofBase.accumulate
.
Keyword argumentinit
is added in Julia 1.5.
Examples
julia> a = Iterators.accumulate(+, [1,2,3,4]);julia> foreach(println, a)13610julia> b = Iterators.accumulate(/, (2, 5, 2, 5); init = 100);julia> collect(b)4-element Vector{Float64}: 50.0 10.0 5.0 1.0
Base.Iterators.reverse
—FunctionIterators.reverse(itr)
Given an iteratoritr
, thenreverse(itr)
is an iterator over the same collection but in the reverse order. This iterator is "lazy" in that it does not make a copy of the collection in order to reverse it; seeBase.reverse
for an eager implementation.
(By default, this returns anIterators.Reverse
object wrappingitr
, which is iterable if the correspondingiterate
methods are defined, but someitr
types may implement more specializedIterators.reverse
behaviors.)
Not all iterator typesT
support reverse-order iteration. IfT
doesn't, then iterating overIterators.reverse(itr::T)
will throw aMethodError
because of the missingiterate
methods forIterators.Reverse{T}
. (To implement these methods, the original iteratoritr::T
can be obtained from anr::Iterators.Reverse{T}
object byr.itr
; more generally, one can useIterators.reverse(r)
.)
Examples
julia> foreach(println, Iterators.reverse(1:5))54321
Base.Iterators.only
—Functiononly(x)
Return the one and only element of collectionx
, or throw anArgumentError
if the collection has zero or multiple elements.
This method requires at least Julia 1.4.
Examples
julia> only(["a"])"a"julia> only("a")'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)julia> only(())ERROR: ArgumentError: Tuple contains 0 elements, must contain exactly 1 elementStacktrace:[...]julia> only(('a', 'b'))ERROR: ArgumentError: Tuple contains 2 elements, must contain exactly 1 elementStacktrace:[...]
Base.Iterators.peel
—Functionpeel(iter)
Returns the first element and an iterator over the remaining elements.
If the iterator is empty returnnothing
(likeiterate
).
Prior versions throw a BoundsError if the iterator is empty.
See also:Iterators.drop
,Iterators.take
.
Examples
julia> (a, rest) = Iterators.peel("abc");julia> a'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)julia> collect(rest)2-element Vector{Char}: 'b': ASCII/Unicode U+0062 (category Ll: Letter, lowercase) 'c': ASCII/Unicode U+0063 (category Ll: Letter, lowercase)
Settings
This document was generated withDocumenter.jl version 1.8.0 onWednesday 9 July 2025. Using Julia version 1.11.6.