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

Asked

Viewed 7,582 times

9

In PHP, to take the last element of a array I can do it like this:

$array = array(1, 2, 3);

echo end($array); // 3;

And in Python? How could I do that with this list:

arr = [1, 2, 3]
  • 9

    Grab it by the ass :)

  • 4

    In python may not be the case, but depending on the species you have to remove the bell first.

2 answers

11


Just take the negative index. It goes for any element, not just the last one. The idea is that it’s actually catching the length plus that value, as it is negative, it will pick up backwards. Obviously the number can not be greater than the length. In this example you could only use -3, which is the list size, and -3 would take the first element. Obviously you can use a variable and be creative.

arr = [1, 2, 3]
print(arr[-1])
print(arr[-2])

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

This is a solution adopted by some languages, so it doesn’t need a specific function or some mathematical juggling, it gets very short and expressive.

9

Puts -1 between square brackets:

arr[-1]

See on Ideone.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.