-5

I know how to do this, but I was wondering which method was more pythionic. The two I have are these:

a = [1, 2, 3, 4, 5]
print a[::-1][0] #Method 1
print a[len(a) - 1] #Method 2

So which is the better of the two to do? They both work.

EDIT

Hi, sorry for the really bad question. I completely forgot about [-1]...

2 Answers2

6

You can use negative indexes to index from the end of a list.

a[-1]
Cyphase
  • 11,502
  • 2
  • 31
  • 32
4

you need to know about python index, how it works:

my_list = [1,2,3,4]

  0  1  2  3    #positive index
  1  2  3  4    # list  element
 -4 -3 -2 -1    # negative index

so if you want last element you can simply do

my_list[-1]
Hackaholic
  • 19,069
  • 5
  • 54
  • 72