alist = []alist[-1] # will generate an IndexError exception whereasalist[-1:] # will return an empty listastr = ''astr[-1] # will generate an IndexError exception whereasastr[-1:] # will return an empty str
>>> empty_list = []>>> tail = empty_list[-1:]>>> if tail:... do_something(tail)
而尝试按索引访问会引发需要处理的IndexError:
>>> empty_list[-1]Traceback (most recent call last):File "<stdin>", line 1, in <module>IndexError: list index out of range
但同样,只有在需要时才应该进行此目的的切片:
创建的新列表
如果之前的列表为空,则新列表为空。
for循环
作为Python的一个特性,for循环中没有内部作用域。
如果您已经对列表执行了完整的迭代,最后一个元素仍然会被循环中分配的变量名引用:
>>> def do_something(arg): pass>>> for item in a_list:... do_something(item)...>>> item'three'
这不是语义上列表中的最后一件事。这是名称item绑定到的最后一件事。
>>> def do_something(arg): raise Exception>>> for item in a_list:... do_something(item)...Traceback (most recent call last):File "<stdin>", line 2, in <module>File "<stdin>", line 1, in do_somethingException>>> item'zero'
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'
a=["first","second","second from last","last"] # A sample listprint(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 listprint(a[-1]) #prints the last item in the list.print(a[-2]) #prints the second last item in the list.