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', '火龙果', '苹果', '百香果']

相关内容:

  1. Python基础教程2c–数据类型-list(列表)
  2. Python基础教程2d–数据类型-tuple(元组)
  3. Python基础教程2h–str,list,tuple,set,dict对比

关注微信公众号:“桔子code”,欢迎后台留言撩我,我会尽我所能为你解惑Python,C等编程知识

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注