简体   繁体   English

获取 IndexError:列表分配索引超出范围

[英]getting IndexError: list assignment index out of range

arr = [1]
arr[0] = arr.pop() 

giving me IndexError: list assignment index out of range i don't understand why?给我 IndexError: list assignment index out of range 我不明白为什么?

By calling arr.pop() it makes arr change to [] , so after that if you try retrieving / chaging item at index 0 it will be out of range since its size is 0通过调用arr.pop()它使arr更改为[] ,因此,如果您尝试在索引0处检索/查询项目,它将超出范围,因为它的大小为0

The right-hand side of an assignment statement is evaluated before the left-hand side.赋值语句的右侧在左侧之前进行评估。 So the list is empty when you try to assign at index 0.因此,当您尝试在索引 0 处分配时,列表为空。

You could rewrite your code roughly as:您可以将代码大致重写为:

arr = [1]
popped = arr.pop()
arr[0] = popped

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM