How to capture the last element of a list in Python?

8

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]
    
asked by anonymous 09.01.2017 / 19:28

2 answers

9

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.

    
09.01.2017 / 19:32
8

Place -1 in brackets:

arr[-1]

See the Ideone .

    
09.01.2017 / 19:32