views:

1320

answers:

3

I found many different ways of getting the last element from a list in python

alist[-1]

alist[len(alist) -1]

Which is the way you would do this?

+30  A: 

someList[-1] is the shortest and most Pythonic. Why complicate things by adding an unnecessary function call in there?

musicfreak
Very nice way. You have to add that this isn't a convenience syntax. You can access every element from a python list this way. So someList[-2] get the second last element and someList[-len(someList)] should give you the first element.
Janusz
+4  A: 

You can also do:

alist.pop()

It depends on what you want to do with your list because the pop() method will delete the last element.

Taurus Olson
+2  A: 

For guidance on issues such as this one, type this at the python prompt:

import this
dangph