DEV Community

Cover image for Julia: Should arrays start with 0 or 1?

Julia: Should arrays start with 0 or 1?

delta456 profile image Swastik Baranwal ・2 min read

Arrays in the Julia programming language are somewhat different from arrays in other programming languages. Not because of different behavior, but because they are start at 1 instead of 0. It's because Julia is used for mathematics , machine learning and scientific etc. Where calculation as mentioned, maybe a bit of confusion when interfacing to the external (non Fortran/Matlab) world but this interfacing doesn't have to be done with arrays if this should be a problem.

If you try to access the array by using zero then it will result an error like the above code:

> [2,3,4,5][0]
ERROR: BoundsError: attempt to access 4-element Array{Int64,1} at index [0]
 [1] getindex(::Array{Int64,1}, ::Int64) at ./array.jl:729
 [2] top-level scope at none:0

But using one works fine

> [2,3,4,5][0]

Arrays should start at 1 because as people count starting from one. The thing with 0-based indexing is that you always then have to write code of the type for i=0:len(a)-1 when iterating. Either ways, there is always some indexing arithmetic.

Most of people would hate Julia arrays because they do not start with 0 like other languages. Most languages are inspired from C so they have array index from 0. There's a special reason especially for C i.e. the name of an array is a pointer, which is a reference to a memory location. Therefore, an expression *(arr + n) or arr[n] locates an element n-locations away from the starting location because the index is used as an offset.

But all languages do not have start with index 0 such as MATLAB, Lua, R etc because most of the tasks that Matlab is used for, e.g. physics and engineering, use the convention of indices starting at 1 in most of the literature, so people working in these fields do not need to convert their algorithms by subtracting 1 from everything.

Hence, I believe that Julia arrays should start from one because it's made for these reasons. But I think array index with 0 are needed because of representation of memory offset as they are stored in continuous addresses especially languages like C, C++ and Java.


Learn more about Julia Arrays:

Discussion (0)

Editor guide