45

From documentation it says firstindex() finds the first index of a collection. Why not just use 1? What could be the case when it's not 1?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Alex Craft
  • 13,598
  • 11
  • 69
  • 133

2 Answers2

51

The first index is not necessarily 1 because Julia supports custom indexing. To understand why it is useful, you can't beat Tim Holy's blog post.

Custom indices allow you to encode information about your data in the indexing pattern itself: sometimes it is more natural to start counting from one, sometimes from zero, sometimes from some more arbitrary number.

Other times, such as when you are writing generic algorithms, you do not really care about the specific index. In which case you can use abstractions such as firstindex, lastindex, and eachindex.

Most often, it is better to avoid referring to an index altogether and just iterate over a collection's elements (e.g. for x in xs).

Julia allows you to use the most effective strategy for your data.

David Sainez
  • 6,446
  • 1
  • 22
  • 45
  • "In which case you can use abstractions such as `firstindex`, `lastindex`, and `eachindex`. You could say that Julia [sets the standards for you](https://www.youtube.com/watch?v=k3KSpeiRPTc)... – Vector Sigma Feb 27 '20 at 19:41
  • 1
    Can you add links to documentation for firstindex(), lastindex(), and eachindex()? – Peter Mortensen Feb 27 '20 at 20:37
16

There are special array types like for example OffsetArrays.jl which can have arbitrary indices.

carstenbauer
  • 9,817
  • 1
  • 27
  • 40