Why `length(2) == length([2])`?

Hi everyone,
What is the idea behind that the legnth of a single number is 1 instead of 0? Does anyone know the reason for that design? On the other hand, we have length([:x])==1, but when typing length(:x), we will get the error message:
ERROR: MethodError: no method matching length(::Symbol)

Numbers are iterable in julia. See for example:

julia> for i in 1
           @show i
       end
i = 1

Therefore having a single number give the correct length it would have if you were to iterate through it makes sense.
See make numbers non-iterable? · Issue #7903 · JuliaLang/julia · GitHub for an old and long discussion of this property.

4 Likes

You might be thinking of the number of dimensions instead. We can check the dimensions (size or axes) and count the number (length of tuple):

julia> length(size(1)), length(size([1]))
(0, 1)
3 Likes