logo

How to Refer to Both Index and Value in Julia's Loops 📂Julia

How to Refer to Both Index and Value in Julia's Loops

Code 1

Base.Iterators.enumerate() returns an iterator that allows referencing both the index and value of an array, similar to Python.

julia> x = [3,5,4,1,2]
5-element Vector{Int64}:
 3
 5
 4
 1
 2

julia> for (idx, value) in enumerate(x)
           println("x[▷eq1◁value")
       end
x[1]: 3
x[2]: 5
x[3]: 4
x[4]: 1
x[5]: 2

julia> typeof(enumerate(x))
Base.Iterators.Enumerate{Vector{Int64}}