Python - 索引错误 : list index out of range NOT being thrown when it should be

标签 python python-3.x index-error

不确定这是因为 Jupyter Notebook 还是 Python 处理了异常,但我正在和 friend 一起解决一个涉及算法的问题

在编写代码时,我使用了 Python!

exampleList = ['a', 'b', 'c', 'd', 'e']

for i in range(0, len(exampleList)):
    for j in range(i + 1, len(exampleList)):
        print(exampleList[i], exampleList[j])

基本上,争论是......这段代码(类似的代码,我用一个简单的例子来说明)涉及两个 for 循环必须抛出错误!因为,索引 i 达到了 len(exampleList) - 1,而索引 j 技术上将变为 len(exampleList)那时,print(exampleList[i], exampleList[j]) 无法工作!看起来在运行代码时,它确实打印得很完美,而且我认为可以处理 IndexError: list index out of range 异常!

我的问题是.. 这应该是 Python 中的预期行为吗?因为和我辩论的那个人最后告诉我‘进行你采访的人注意到了这些事情!你必须能够解释每一行。”

我想了解这部分是如何处理的,这样我就可以解释为什么这不会引发错误!

最佳答案

range 函数包含下限,但不包含上限。

您的示例列表有 5 个元素。这意味着第一个循环正在运行 range(0,5),使最大值 i=4。这使得第二个循环的最大值为 range(5,5),这是一个空列表。迭代空列表会导致 0 次迭代。

>>> exampleList = ['a', 'b', 'c', 'd', 'e']
>>> len(exampleList)
5
>>> range(0, 5)
[0, 1, 2, 3, 4]
>>> range(5,5)
[]

关于Python - 索引错误 : list index out of range NOT being thrown when it should be,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51382748/

相关文章:

python - 如何在Python中获得系统显示分辨率的宽高比?

python - 寻找一种有效的方法或算法来检查文件是否属于某个文件夹路径列表中的某个项目

python - 对象旁边的方括号 - 表示法叫什么?

python 3.6 "IndexError: list index out of range"

PHP(或PYTHON)将所有包含的文件合并到一个大文件中(递归?)

python - python 中的预自增运算符

python - Django Admin - 'ManyToManyField' 对象没有属性 'through'

python - 默认为并选择 Tkinter 列表框中的第一项

Python索引错误: list index out of range when using a list as an iterable

Python 字符串递归,字符串索引超出范围