Difference handling missing of enumerate and eachindex

The following behavior has cost me 6 hours of debugging. Is there a reason enumerate and eachindex handle the skipmissing itorator differently?

julia> a = [missing, missing, missing, missing, missing, missing, missing, 5, missing, missing, missing, missing, missing]
13-element Vector{Union{Missing, Int64}}:
  missing
  missing
  missing
  missing
  missing
  missing
  missing
 5
  missing
  missing
  missing
  missing
  missing

julia> for i in eachindex(skipmissing(a))
       @show i
       end
i = 8

julia> for (i, b) in enumerate(skipmissing(a))
       @show i
       end
i = 1

Generated with julia 1.7.0.

They are two different things: eachindex gives you (valid) indices that you can index with, enumerate just counts from 1 for any arbitrary iterator.

Here is another, perhaps more illustrative, example:

julia> using OffsetArrays

julia> v = OffsetVector([1, 2, 3], -1);

julia> for (i, _) in enumerate(v)
           @show i
       end
i = 1
i = 2
i = 3

julia> for i in eachindex(v)
           @show i
       end
i = 0
i = 1
i = 2

(It is preffered to just copy and paste your code instead of including a screenshot – images are not searchable, and it is not possible for people that want to help to copy the code and play around. In this case you did both, but the image doesn’t really add anything.)

3 Likes

Thanks for the feedback! It also explains the name: “enumerate”.

You might also be interested in

julia> for (i, b) in pairs(skipmissing(a))
           @show i
       end
i = 8
2 Likes