How do I access the last element of an array?
Asked Answered
F

2

9

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?

Franfranc answered 13/1, 2020 at 19:10 Comment(0)
F
17

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)].

Franfranc answered 13/1, 2020 at 19:10 Comment(2)
It's also worth pointing out that A[end] is just a syntactic sugar for A[lastindex(A)], they're equivalent.Yarrow
Good point. I've edited the answer to make that more clear. thanks!Franfranc
C
4

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)

Chit answered 14/3, 2023 at 9:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.