In PHP, to get the last element of an array I can do this:
$array = array(1, 2, 3);
echo end($array); // 3;
What about Python? How could I do this with this list:
arr = [1, 2, 3]
In PHP, to get the last element of an array I can do this:
$array = array(1, 2, 3);
echo end($array); // 3;
What about Python? How could I do this with this list:
arr = [1, 2, 3]
Just grab the negative index. Worth for any element, not just the latter. The idea is that in fact he is taking length
plus that value, as it is negative, it goes upside down. Obviously the number can not be greater than length
. In this example you could only use -3, which is the size of the list, and -3 would pick up the first element. You can obviously use a variable and be creative.
arr = [1, 2, 3]
print(arr[-1])
print(arr[-2])
See running on ideone .
This is a solution adopted by some languages, so it does not need a specific function or some mathematical juggling, it gets very short and expressive.