Negative index

2 snippets across 2 stacks — JavaScript, Python

JSJavaScript

Array/String .at() Method

JS · Modern Features
syntax
arr.at(index)
str.at(index)
example
const stack = ["first", "second", "third", "last"];
console.log(stack.at(0));   // "first"
console.log(stack.at(-1));  // "last"
console.log(stack.at(-2));  // "third"

console.log("hello".at(-1)); // "o"

Note Works on Arrays, Strings, and TypedArrays. The main advantage over bracket notation is support for negative indices.

PYPython

Indexing & Negative Indexing

PY · Lists
syntax
items[index]
items[-index]
example
fruits = ["apple", "banana", "cherry", "date"]
print(fruits[0])
print(fruits[-1])
print(fruits[-2])
output
apple
date
cherry

Note Index 0 is the first element, -1 is the last. Accessing an index beyond the list length raises IndexError.