name[end] gives you the last value. But when I learned it, I could’ve sworn there was a keyword for the very first value. Obviously you can just index at one, but does that keyword exist? Or did I make it up?
If I recall correctly, that would be ‘’ arrayname[begin], but checking this on my phone is a bit tricky.
3 Likes
While begin and end are used to create a block of code, they can also be used as “indices” to safely get the first and last elements of a collection. While Arrays do index starting at 1, that’s not always the case e.g. OffsetArrays.jl or just because getindex is a function for which an abitrary method could be created e.g. Base.getindex() = 2 (wow I hate that).
From the documentation
begin
begin...end denotes a block of code.
begin
println("Hello, ")
println("World!")
end
Usually begin will not be necessary, since keywords such as function and let implicitly begin blocks of code. See also ;.
begin may also be used when indexing to represent the first index of a collection or the first index of a dimension of an array. For example, a[begin]
is the first element of an array a.
│ Julia 1.4
│
│ Use of begin as an index requires Julia 1.4 or later.
Examples
≡≡≡≡≡≡≡≡
julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> A[begin, :]
2-element Matrix{Int64}:
1
2
Similarly for end
end
end marks the conclusion of a block of expressions, for example module, struct, mutable struct, begin, let, for etc.
end may also be used when indexing to represent the last index of a collection or the last index of a dimension of an array.
Examples
≡≡≡≡≡≡≡≡
julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> A[end, :]
2-element Vector{Int64}:
3
4
2 Likes