04-负数索引
4.1.2 负数索引
虽然索引从0开始并向上增长,但也可以用负整数作为索引。整数值 -1
指的是列表中的最后一个索引, -2
指的是列表中倒数第二个索引,以此类推。在交互式环境中输入以下代码:
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[-1]
'elephant'
>>> spam[-3]
'bat'
>>> 'The ' + spam[-1] + ' is afraid of the ' + spam[-3] + '.'
'The elephant is afraid of the bat.'