I want to access the last element of some array.
I am using length
:
last_element = x[length(x)]
Is this correct? Is there a canonical way to access the last element of an ordered collection in Julia?
I want to access the last element of some array.
I am using length
:
last_element = x[length(x)]
Is this correct? Is there a canonical way to access the last element of an ordered collection in Julia?
length
is fine if your array uses standard indexing. However, x[length(x)]
will not necessarily return the last element if the array uses custom indexing.
A more general and explicit method is to use last
, which will return the last element of an array regardless of indexing scheme:
julia> x = rand(3)
3-element Array{Float64,1}:
0.7633644675721114
0.396645489023141
0.4086436862248366
julia> last(x)
0.4086436862248366
If you need the index of the last element, use lastindex
:
julia> lastindex(x)
3
The following three methods are equivalent:
julia> last(x)
0.4086436862248366
julia> x[lastindex(x)]
0.4086436862248366
julia> x[end]
0.4086436862248366
x[end]
is syntax sugar for x[lastindex(x)]
.
The ´end´ syntax also allows you to access the second last element etc. I cannot add a comment so i make this Answer.
A[end] # last element
A[end-1] # second last
A[end-9] # 10th last
(provided they exist)
© 2022 - 2024 — McMap. All rights reserved.
A[end]
is just a syntactic sugar forA[lastindex(A)]
, they're equivalent. – Yarrow