Python错误集锦:调用列表的元素时提示IndexError: list assignment index out of range

原文链接:http://www.juzicode.com/archives/2692

错误提示: 

调用列表的元素时提示:IndexError: list assignment index out of range

#juzicode.com/vx:桔子code
lst = ['juzicode','香蕉','苹果','西瓜']
lst[1] = '火龙果'
print('lst:',lst)
lst[4] = '百香果'
print('lst:',lst)
lst: ['juzicode', '火龙果', '苹果', '西瓜']
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-7-b54d5e24c315> in <module>
      3 lst[1] = '火龙果'
      4 print('lst:',lst)
----> 5 lst[4] = '百香果'
      6 print('lst:',lst)

IndexError: list assignment index out of range

可能原因:

1、前面例子中list的长度为4,其下标志是从0开始的,有0,1,2,3等4个取值,大于3的下标都是错误的。

 

解决方法:

1、按照索引位置修改必须要清除待修改元素的位置号,前面例子中可能本意是要修改第4个元素,下标则应该使用lst[3]

#juzicode.com/vx:桔子code
lst = ['juzicode','香蕉','苹果','西瓜']
lst[1] = '火龙果'
print('lst:',lst)
lst[3] = '百香果'
print('lst:',lst)
lst: ['juzicode', '火龙果', '苹果', '西瓜']
lst: ['juzicode', '火龙果', '苹果', '百香果']
posted @ 2020-12-19 11:27  桔子code  阅读(484)  评论(0编辑  收藏  举报