Getting the last element of a list in Python

在Python中,你如何得到列表的最后一个元素?


some_list[-1] is the shortest and most Pythonic.

In fact, you can do much more with this syntax. The some_list[-n] syntax gets the nth-to-last element. So some_list[-1] gets the last element, some_list[-2] gets the second to last, etc, all the way down to some_list[-len(some_list)] , which gives you the first element.

You can also set list elements in this way. For instance:

>>> some_list = [1, 2, 3]
>>> some_list[-1] = 5 # Set the last element
>>> some_list[-2] = 3 # Set the second to last element
>>> some_list
[1, 3, 5]

If your str() or list() objects might end up being empty as so: astr = '' or alist = [] , then you might want to use alist[-1:] instead of alist[-1] for object "sameness".

The significance of this is:

alist = []
alist[-1]   # will generate an IndexError exception whereas 
alist[-1:]  # will return an empty list
astr = ''
astr[-1]    # will generate an IndexError exception whereas
astr[-1:]   # will return an empty str

Where the distinction being made is that returning an empty list object or empty str object is more "last element"-like then an exception object.


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.

链接地址: http://www.djcxy.com/p/3128.html

上一篇: 从Python列表中列出一个扁平列表

下一篇: 在Python中获取列表的最后一个元素