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)]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With