enumerate
enumerate(iter)
An iterator that yields (i, x)
where i
is an index starting at 1, and
x
is the i
th 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")
end
1 a
2 b
3 c
Examples
julia> a = ["a", "b", "c"];
for (index, value) in enumerate(a)
println("$index $value")
end
1 a
2 b
3 c
julia> foo = [-1, -2, -3];
julia> for (index, value) in enumerate(foo)
println("Element at index $index : $value")
end
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")
end
Index: 1, Value: 10
Index: 2, Value: 20
Index: 3, Value: 30
Index: 4, Value: 40
Index: 5, Value: 50
- Enumerate elements of an array:
julia> fruits = ["apple", "banana", "orange", "grape"];
julia> for (i, fruit) in enumerate(fruits)
println("Index: $i, Fruit: $fruit")
end
Index: 1, Fruit: apple
Index: 2, Fruit: banana
Index: 3, Fruit: orange
Index: 4, Fruit: grape
- Accessing only the indices:
julia> for (i, _) in enumerate(["a", "b", "c"])
println("Index: $i")
end
Index: 1
Index: 2
Index: 3
- Using enumerate with a range:
julia> for (i, num) in enumerate(1:5)
println("Index: $i, Number: $num")
end
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")
end
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.