Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access the last element of an array?

Tags:

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?

like image 409
David Varela Avatar asked Jan 13 '20 19:01

David Varela


1 Answers

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

like image 136
David Varela Avatar answered Sep 20 '22 13:09

David Varela