An iterator that yields (i, x) where i is an index 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 index i of the iterations.

julia> a = ["a", "b", "c"];

julia> for (index, value) in enumerate(a)
           println("$index $value")
1 a
2 b
3 c


julia> a = ["a", "b", "c"];
       for (index, value) in enumerate(a)
           println("$index $value")
1 a
2 b
3 c
julia> foo = [-1, -2, -3];
julia> for (index, value) in enumerate(foo)
            println("Element at index $index : $value")
Element at index 1 : -1
Element at index 2 : -2
Element at index 3 : -3
julia> a = [10, 20, 30, 40, 50];

julia> for (i, x) in enumerate(a)
           println("Index: $i, Value: $x")
Index: 1, Value: 10
Index: 2, Value: 20
Index: 3, Value: 30
Index: 4, Value: 40
Index: 5, Value: 50
  1. Enumerate elements of an array:
julia> fruits = ["apple", "banana", "orange", "grape"];

julia> for (i, fruit) in enumerate(fruits)
           println("Index: $i, Fruit: $fruit")
Index: 1, Fruit: apple
Index: 2, Fruit: banana
Index: 3, Fruit: orange
Index: 4, Fruit: grape
  1. Accessing only the indices:
julia> for (i, _) in enumerate(["a", "b", "c"])
           println("Index: $i")
Index: 1
Index: 2
Index: 3
  1. Using enumerate with a range:
julia> for (i, num) in enumerate(1:5)
           println("Index: $i, Number: $num")
Index: 1, Number: 1
Index: 2, Number: 2
Index: 3, Number: 3
Index: 4, Number: 4
Index: 5, Number: 5

Common mistake example:

julia> for (index, value) in enumerate(10)
           println("Index: $index, Value: $value")
ERROR: MethodError: no method matching iterate(::Int64)

In this example, the enumerate function is used on a single integer value. enumerate expects an iterable object as its argument. To avoid this error, make sure to pass an iterable collection like an array or a range to enumerate.

See Also

countfrom, cycle, done, drop, eachindex, enumerate, first, repeated, rest, start, svds, take, vecdot, vecnorm, zip,

User Contributed Notes

Add a Note

The format of note supported is markdown, use triple backtick to start and end a code block.

*Required Field

Checking you are not a robot: