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

首选哪种方式?

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

当前回答

在Python中访问列表中的最后一个元素:

1:使用负索引访问最后一个元素-1

>> data = ['s','t','a','c','k','o','v','e','r','f','l','o','w']
>> data[-1]
'w'

2.使用pop()方法访问最后一个元素

>> data = ['s','t','a','c','k','o','v','e','r','f','l','o','w']
>> data.pop()
'w'

然而,pop方法将从列表中删除最后一个元素。

其他回答

要防止IndexError:list索引超出范围,请使用以下语法:

mylist = [1, 2, 3, 4]

# With None as default value:
value = mylist and mylist[-1]

# With specified default value (option 1):
value = mylist and mylist[-1] or 'default'

# With specified default value (option 2):
value = mylist[-1] if mylist else 'default'

奇怪的是还没有人发布这个:

>>> l = [1, 2, 3]
>>> *x, last_elem = l
>>> last_elem
3
>>> 

打开包装。

您只需获取并放入[-1]索引即可。例如:

list=[0,1,2]
last_index=list[-1]
print(last_index)

您将得到2作为输出。

如果str()或list()对象最终可能为空:astr=“”或alist=[],那么您可能希望使用alist[-1:]而不是alist[-1]来表示对象“sameness”。

其意义在于:

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

区别在于,返回空列表对象或空str对象更像是“最后一个元素”,而不是异常对象。

另一种方法:

some_list.reverse() 
some_list[0]