如何获取列表的最后一个元素?

首选哪种方式?

alist[-1]
alist[len(alist) - 1]

当前回答

为了避免“IndexError:列表索引超出范围”,可以使用这段代码。

list_values = [12, 112, 443]

def getLastElement(lst):
    if len(lst) == 0:
        return 0
    else:
        return lst[-1]

print(getLastElement(list_values))

其他回答

您还可以执行以下操作:

last_elem = alist.pop()

这取决于您想对列表做什么,因为pop()方法将删除最后一个元素。

some_list[-1]是最短、最Python的。

事实上,使用这种语法可以做得更多。some_list[-n]语法获取倒数第n个元素。因此,some_list[-1]获取最后一个元素,some_list[-2]获取倒数第二个元素,等等,一直到some_list[-len(some_list)],这为您提供了第一个元素。

也可以用这种方式设置列表元素。例如:

>>> 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]

注意,如果期望的项不存在,则通过索引获取列表项将引发IndexError。这意味着如果some_list为空,some_list[-1]将引发异常,因为空列表不能有最后一个元素。

在python中显示最后一个元素的最简单方法是

>>> list[-1:] # returns indexed value
    [3]
>>> list[-1]  # returns value
    3

有许多其他方法可以实现这一目标,但这些方法使用起来既简单又方便。

这是您查询的解决方案。

a=["first","second","second from last","last"] # A sample list
print(a[0]) #prints the first item in the list because the index of the list always starts from 0.
print(a[1]) #prints second item in list 
print(a[-1]) #prints the last item in the list.
print(a[-2]) #prints the second last item in the list.

输出:

>>> first
>>> second
>>> last
>>> second from last

lst[-1]是最好的方法,但对于一般的可迭代项,请考虑more_itertools.last:

Code

import more_itertools as mit


mit.last([0, 1, 2, 3])
# 3

mit.last(iter([1, 2, 3]))
# 3

mit.last([], "some default")
# 'some default'