3

Very simple question, I have a list like so:

a = [0,1,2,3,4,5,7,8]

and I need to get the last item in that list as a float or an integer. If I do:

print a[0], a[4]

I get 1 5, which is fine, but if i try to retrieve the last item with:

print a[-1:]

I get the list [8] instead of the number 8. I know that I could just use print a[len(a)-1] but it feels kind of overkill and now I also have the doubt of why is a[-1:] returning a list instead of an element?

Gabriel
  • 40,504
  • 73
  • 230
  • 404

3 Answers3

12

You need to do a[-1] to get the last item. See below:

>>> a = [0,1,2,3,4,5,7,8]
>>> a[-1]
8
>>>

Having the colon in there makes it slice the list, not index it.

Here are some references on lists and slicing/indexing them:

http://docs.python.org/2/tutorial/introduction.html#lists

Explain Python's slice notation

Community
  • 1
  • 1
3

Just do:

>>> a = [0,1,2,3,4,5,7,8]
>>> a[-1]
 8

You were slicing the list not getting last item.

jabaldonedo
  • 25,822
  • 8
  • 77
  • 77
0

Simplest way:

>>> a = [0,1,2,3,4,5,7,8]
>>> a[-1]
8

why is a[-1:] returning a list instead of an element?

>>> list[-1:] # returns list
    [8]
>>> list[-1]  # returns value
    8

we also can use pop(). But it removes last element from the list.So it depends what you want to do.

list.pop()
Harsha Biyani
  • 7,049
  • 9
  • 37
  • 61