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?
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:
Just do:
>>> a = [0,1,2,3,4,5,7,8]
>>> a[-1]
8
You were slicing the list not getting last item.
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.