Is there any way to do this in Julia?
#Python
lst = [1, 2, 3]
print(lst[-2]) # prints out 2
I know last function gets the last one, but I want to get the second one from the last.
Thanks!!
Is there any way to do this in Julia?
#Python
lst = [1, 2, 3]
print(lst[-2]) # prints out 2
I know last function gets the last one, but I want to get the second one from the last.
Thanks!!
Within the context of array indexing, end can be used as a special syntax to represent the last index of the array, whatever that may be. So lst[end-1] is what you're looking for.
julia> lst = [1, 2, 3];
julia> lst[end-1]
2
You might want to check out the Python section of Julia's "Noteworthy Differences from Other Languages" page. A few of the relevant notes from that page:
- Julia does not support negative indices. In particular, the last element of a list or array is indexed with
endin Julia, not-1as in Python.- Julia requires end for indexing until the last element.
x[1:]in Python is equivalent tox[2:end]in Julia.