Tip: use eachindex when iterating over arrays

326 views
Skip to first unread message

Tim Holy

unread,
Apr 19, 2015, 9:47:13 PM4/19/15
to julia...@googlegroups.com
For those of you wanting to write code that will perform well on different
AbstractArray types, starting with julia 0.4 it will be recommended that you
should typically write

for i in eachindex(A)
# do something with i and/or A[i]
end

rather than

for i = 1:length(A)
# do something with i and/or A[i]
end

The syntax

for a in A
# do something with a
end

is unchanged.

If you're using julia 0.3, the Compat package (starting with version 0.4.1)
defines `eachindex(A) = 1:length(A)`, so if you're willing to use Compat you
can already start using this syntax.


This will make a difference, in julia 0.4, when indexing arrays for which a
single linear index is inefficient---in such cases, `i` will be a
multidimensional index object. You can still say `A[i]`, and it will likely be
several times faster than if `i` were an integer. In contrast, if `A` is an
array for which linear indexing is fast, then `eachindex(A) = 1:length(A)` as
previously.

You can read more about this in the documentation for multidimensional arrays
in julia 0.4:
http://docs.julialang.org/en/latest/manual/arrays/

This public service announcement has been sponsored by the Department of
Arrays and Array Indexing.

Best,
--Tim

Dahua Lin

unread,
Apr 19, 2015, 10:56:57 PM4/19/15
to julia...@googlegroups.com
Thanks for the great work!

Dahua

Christian Peel

unread,
Apr 19, 2015, 11:26:13 PM4/19/15
to julia-users
Thanks for the PSA; I'd enjoy more of them.
Reply all
Reply to author
Forward
0 new messages