Iteration utilities

Base.Iterators.Stateful — Type

  1. Stateful(itr)

There are several different ways to think about this iterator wrapper:

  1. It provides a mutable wrapper around an iterator and its iteration state.
  2. It turns an iterator-like abstraction into a Channel-like abstraction.
  3. It’s an iterator that mutates to become its own rest iterator whenever an item is produced.

Stateful provides the regular iterator interface. Like other mutable iterators (e.g. Base.Channel), if iteration is stopped early (e.g. by a break in a for 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

  1. julia> a = Iterators.Stateful("abcdef");
  2. julia> isempty(a)
  3. false
  4. julia> popfirst!(a)
  5. 'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)
  6. julia> collect(Iterators.take(a, 3))
  7. 3-element Vector{Char}:
  8. 'b': ASCII/Unicode U+0062 (category Ll: Letter, lowercase)
  9. 'c': ASCII/Unicode U+0063 (category Ll: Letter, lowercase)
  10. 'd': ASCII/Unicode U+0064 (category Ll: Letter, lowercase)
  11. julia> collect(a)
  12. 2-element Vector{Char}:
  13. 'e': ASCII/Unicode U+0065 (category Ll: Letter, lowercase)
  14. 'f': ASCII/Unicode U+0066 (category Ll: Letter, lowercase)
  15. julia> Iterators.reset!(a); popfirst!(a)
  16. 'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)
  17. julia> Iterators.reset!(a, "hello"); popfirst!(a)
  18. 'h': ASCII/Unicode U+0068 (category Ll: Letter, lowercase)
  1. julia> a = Iterators.Stateful([1,1,1,2,3,4]);
  2. julia> for x in a; x == 1 || break; end
  3. julia> peek(a)
  4. 3
  5. julia> sum(a) # Sum the remaining elements
  6. 7

source

Base.Iterators.zip — Function

  1. zip(iters...)

Run multiple iterators at the same time, until any of them is exhausted. The value type of the zip iterator is a tuple of values of its subiterators.

Note

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.

Note

zip() with no arguments yields an infinite iterator of empty tuples.

See also: enumerate, Base.splat.

Examples

  1. julia> a = 1:5
  2. 1:5
  3. julia> b = ["e","d","b","c","a"]
  4. 5-element Vector{String}:
  5. "e"
  6. "d"
  7. "b"
  8. "c"
  9. "a"
  10. julia> c = zip(a,b)
  11. zip(1:5, ["e", "d", "b", "c", "a"])
  12. julia> length(c)
  13. 5
  14. julia> first(c)
  15. (1, "e")

source

Base.Iterators.enumerate — Function

  1. enumerate(iter)

An iterator that yields (i, x) where i is a counter starting at 1, and x is the ith value from the given iterator. It’s useful when you need not only the values x over which you are iterating, but also the number of iterations so far.

Note that i may not be valid for indexing iter, or may index a different element. This will happen if iter has indices that do not start at 1, and may happen for strings, dictionaries, etc. See the pairs(IndexLinear(), iter) method if you want to ensure that i is an index.

Examples

  1. julia> a = ["a", "b", "c"];
  2. julia> for (index, value) in enumerate(a)
  3. println("$index $value")
  4. end
  5. 1 a
  6. 2 b
  7. 3 c
  8. julia> str = "naïve";
  9. julia> for (i, val) in enumerate(str)
  10. print("i = ", i, ", val = ", val, ", ")
  11. try @show(str[i]) catch e println(e) end
  12. end
  13. i = 1, val = n, str[i] = 'n'
  14. i = 2, val = a, str[i] = 'a'
  15. i = 3, val = ï, str[i] = 'ï'
  16. i = 4, val = v, StringIndexError("naïve", 4)
  17. i = 5, val = e, str[i] = 'v'

source

Base.Iterators.rest — Function

  1. rest(iter, state)

An iterator that yields the same elements as iter, but starting at the given state.

See also: Iterators.drop, Iterators.peel, Base.rest.

Examples

  1. julia> collect(Iterators.rest([1,2,3,4], 2))
  2. 3-element Vector{Int64}:
  3. 2
  4. 3
  5. 4

source

Base.Iterators.countfrom — Function

  1. countfrom(start=1, step=1)

An iterator that counts forever, starting at start and incrementing by step.

Examples

  1. julia> for v in Iterators.countfrom(5, 2)
  2. v > 10 && break
  3. println(v)
  4. end
  5. 5
  6. 7
  7. 9

source

Base.Iterators.take — Function

  1. take(iter, n)

An iterator that generates at most the first n elements of iter.

See also: drop, peel, first, Base.take!.

Examples

  1. julia> a = 1:2:11
  2. 1:2:11
  3. julia> collect(a)
  4. 6-element Vector{Int64}:
  5. 1
  6. 3
  7. 5
  8. 7
  9. 9
  10. 11
  11. julia> collect(Iterators.take(a,3))
  12. 3-element Vector{Int64}:
  13. 1
  14. 3
  15. 5

source

Base.Iterators.takewhile — Function

  1. takewhile(pred, iter)

An iterator that generates element from iter as long as predicate pred is true, afterwards, drops every element.

Julia 1.4

This function requires at least Julia 1.4.

Examples

  1. julia> s = collect(1:5)
  2. 5-element Vector{Int64}:
  3. 1
  4. 2
  5. 3
  6. 4
  7. 5
  8. julia> collect(Iterators.takewhile(<(3),s))
  9. 2-element Vector{Int64}:
  10. 1
  11. 2

source

Base.Iterators.drop — Function

  1. drop(iter, n)

An iterator that generates all but the first n elements of iter.

Examples

  1. julia> a = 1:2:11
  2. 1:2:11
  3. julia> collect(a)
  4. 6-element Vector{Int64}:
  5. 1
  6. 3
  7. 5
  8. 7
  9. 9
  10. 11
  11. julia> collect(Iterators.drop(a,4))
  12. 2-element Vector{Int64}:
  13. 9
  14. 11

source

Base.Iterators.dropwhile — Function

  1. dropwhile(pred, iter)

An iterator that drops element from iter as long as predicate pred is true, afterwards, returns every element.

Julia 1.4

This function requires at least Julia 1.4.

Examples

  1. julia> s = collect(1:5)
  2. 5-element Vector{Int64}:
  3. 1
  4. 2
  5. 3
  6. 4
  7. 5
  8. julia> collect(Iterators.dropwhile(<(3),s))
  9. 3-element Vector{Int64}:
  10. 3
  11. 4
  12. 5

source

Base.Iterators.cycle — Function

  1. cycle(iter)

An iterator that cycles through iter forever. If iter is empty, so is cycle(iter).

See also: Iterators.repeated, Base.repeat.

Examples

  1. julia> for (i, v) in enumerate(Iterators.cycle("hello"))
  2. print(v)
  3. i > 10 && break
  4. end
  5. hellohelloh

source

Base.Iterators.repeated — Function

  1. repeated(x[, n::Int])

An iterator that generates the value x forever. If n is specified, generates x that many times (equivalent to take(repeated(x), n)).

See also: Iterators.cycle, Base.repeat.

Examples

  1. julia> a = Iterators.repeated([1 2], 4);
  2. julia> collect(a)
  3. 4-element Vector{Matrix{Int64}}:
  4. [1 2]
  5. [1 2]
  6. [1 2]
  7. [1 2]

source

Base.Iterators.product — Function

  1. product(iters...)

Return an iterator over the product of several iterators. Each generated element is a tuple whose ith element comes from the ith argument iterator. The first iterator changes the fastest.

See also: zip, Iterators.flatten.

Examples

  1. julia> collect(Iterators.product(1:2, 3:5))
  2. 2×3 Matrix{Tuple{Int64, Int64}}:
  3. (1, 3) (1, 4) (1, 5)
  4. (2, 3) (2, 4) (2, 5)
  5. julia> ans == [(x,y) for x in 1:2, y in 3:5] # collects a generator involving Iterators.product
  6. true

source

Base.Iterators.flatten — Function

  1. flatten(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

  1. julia> collect(Iterators.flatten((1:2, 8:9)))
  2. 4-element Vector{Int64}:
  3. 1
  4. 2
  5. 8
  6. 9
  7. julia> [(x,y) for x in 0:1 for y in 'a':'c'] # collects generators involving Iterators.flatten
  8. 6-element Vector{Tuple{Int64, Char}}:
  9. (0, 'a')
  10. (0, 'b')
  11. (0, 'c')
  12. (1, 'a')
  13. (1, 'b')
  14. (1, 'c')

source

Base.Iterators.flatmap — Function

  1. Iterators.flatmap(f, iterators...)

Equivalent to flatten(map(f, iterators...)).

See also Iterators.flatten, Iterators.map.

Julia 1.9

This function was added in Julia 1.9.

Examples

  1. julia> Iterators.flatmap(n -> -n:2:n, 1:3) |> collect
  2. 9-element Vector{Int64}:
  3. -1
  4. 1
  5. -2
  6. 0
  7. 2
  8. -3
  9. -1
  10. 1
  11. 3
  12. julia> stack(n -> -n:2:n, 1:3)
  13. ERROR: DimensionMismatch: stack expects uniform slices, got axes(x) == (1:3,) while first had (1:2,)
  14. [...]
  15. julia> Iterators.flatmap(n -> (-n, 10n), 1:2) |> collect
  16. 4-element Vector{Int64}:
  17. -1
  18. 10
  19. -2
  20. 20
  21. julia> ans == vec(stack(n -> (-n, 10n), 1:2))
  22. true

source

Base.Iterators.partition — Function

  1. partition(collection, n)

Iterate over a collection n elements at a time.

Examples

  1. julia> collect(Iterators.partition([1,2,3,4,5], 2))
  2. 3-element Vector{SubArray{Int64, 1, Vector{Int64}, Tuple{UnitRange{Int64}}, true}}:
  3. [1, 2]
  4. [3, 4]
  5. [5]

source

Base.Iterators.map — Function

  1. Iterators.map(f, iterators...)

Create a lazy mapping. This is another syntax for writing (f(args...) for args in zip(iterators...)).

Julia 1.6

This function requires at least Julia 1.6.

Examples

  1. julia> collect(Iterators.map(x -> x^2, 1:3))
  2. 3-element Vector{Int64}:
  3. 1
  4. 4
  5. 9

source

Base.Iterators.filter — Function

  1. Iterators.filter(flt, itr)

Given a predicate function flt and an iterable object itr, return an iterable object which upon iteration yields the elements x of itr that satisfy flt(x). The order of the original iterator is preserved.

This function is lazy; that is, it is guaranteed to return in $Θ(1)$ time and use $Θ(1)$ additional space, and flt will not be called by an invocation of filter. Calls to flt will be made when iterating over the returned iterable object. These calls are not cached and repeated calls will be made when reiterating.

See Base.filter for an eager implementation of filtering for arrays.

Examples

  1. julia> f = Iterators.filter(isodd, [1, 2, 3, 4, 5])
  2. Base.Iterators.Filter{typeof(isodd), Vector{Int64}}(isodd, [1, 2, 3, 4, 5])
  3. julia> foreach(println, f)
  4. 1
  5. 3
  6. 5
  7. julia> [x for x in [1, 2, 3, 4, 5] if isodd(x)] # collects a generator over Iterators.filter
  8. 3-element Vector{Int64}:
  9. 1
  10. 3
  11. 5

source

Base.Iterators.accumulate — Function

  1. Iterators.accumulate(f, itr; [init])

Given a 2-argument function f and an iterator itr, return a new iterator that successively applies f to the previous value and the next element of itr.

This is effectively a lazy version of Base.accumulate.

Julia 1.5

Keyword argument init is added in Julia 1.5.

Examples

  1. julia> a = Iterators.accumulate(+, [1,2,3,4]);
  2. julia> foreach(println, a)
  3. 1
  4. 3
  5. 6
  6. 10
  7. julia> b = Iterators.accumulate(/, (2, 5, 2, 5); init = 100);
  8. julia> collect(b)
  9. 4-element Vector{Float64}:
  10. 50.0
  11. 10.0
  12. 5.0
  13. 1.0

source

Base.Iterators.reverse — Function

  1. Iterators.reverse(itr)

Given an iterator itr, then reverse(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; see Base.reverse for an eager implementation.

(By default, this returns an Iterators.Reverse object wrapping itr, which is iterable if the corresponding iterate methods are defined, but some itr types may implement more specialized Iterators.reverse behaviors.)

Not all iterator types T support reverse-order iteration. If T doesn’t, then iterating over Iterators.reverse(itr::T) will throw a MethodError because of the missing iterate methods for Iterators.Reverse{T}. (To implement these methods, the original iterator itr::T can be obtained from an r::Iterators.Reverse{T} object by r.itr; more generally, one can use Iterators.reverse(r).)

Examples

  1. julia> foreach(println, Iterators.reverse(1:5))
  2. 5
  3. 4
  4. 3
  5. 2
  6. 1

source

Base.Iterators.only — Function

  1. only(x)

Return the one and only element of collection x, or throw an ArgumentError if the collection has zero or multiple elements.

See also first, last.

Julia 1.4

This method requires at least Julia 1.4.

Examples

  1. julia> only(["a"])
  2. "a"
  3. julia> only("a")
  4. 'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)
  5. julia> only(())
  6. ERROR: ArgumentError: Tuple contains 0 elements, must contain exactly 1 element
  7. Stacktrace:
  8. [...]
  9. julia> only(('a', 'b'))
  10. ERROR: ArgumentError: Tuple contains 2 elements, must contain exactly 1 element
  11. Stacktrace:
  12. [...]

source

Base.Iterators.peel — Function

  1. peel(iter)

Returns the first element and an iterator over the remaining elements.

If the iterator is empty return nothing (like iterate).

Julia 1.7

Prior versions throw a BoundsError if the iterator is empty.

See also: Iterators.drop, Iterators.take.

Examples

  1. julia> (a, rest) = Iterators.peel("abc");
  2. julia> a
  3. 'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)
  4. julia> collect(rest)
  5. 2-element Vector{Char}:
  6. 'b': ASCII/Unicode U+0062 (category Ll: Letter, lowercase)
  7. 'c': ASCII/Unicode U+0063 (category Ll: Letter, lowercase)

source