分配一个值以按索引列出超出范围 [英] Assigning a value to list by index out of range

查看:43
本文介绍了分配一个值以按索引列出超出范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

mylist = ["a", "apple", "b", "ball", "c", "cat"]
mylist[6] = "value"
print(mylist)

错误:

IndexError: list assignment index out of range

我记得在javascript中按索引分配值,在python中不起作用吗?

I remember assigning values by index in javascript, it doesn't work in python?

推荐答案

在python中,如果索引不存在,则单个分配不起作用.Javascript数组是稀疏" ,您可以将值存储在任何索引中.取而代之的是,python列表具有定义的大小,并且仅在现有索引中才允许赋值.

In python single assignment does not work if the index does not exist. Javascript arrays are "sparse", you can stash a value at any index. Instead, python lists have a defined size, and assignment is only allowed in existing indices.

如果要在末尾添加,请使用 mylist.append(value)

If you want to add at the end, use mylist.append(value),

这篇关于分配一个值以按索引列出超出范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆