为什么枚举不给我索引错误?

Python没有为此for循环给我一个索引错误:

s = ['one', 'two']

for index, char in enumerate(s):
    if s[index - 1] != ' ' or s[index + 1212] != ' ':
        pass

但是随着条件的改变,它确实给了我一个索引错误:

s = ['one', 'two']

for index, char in enumerate(s):
    if s[index + 1212] != ' ' or s[index - 1] != ' ':
        pass

有人在解释吗?

评论
  • ket
    ket 回复

    In most programming languages, including Python, boolean expressions are evaluated one part at a time, and the evaluation stops as soon as one of the parts is false. This is called "short-circuit evaluation" or "minimal evaluation".

    In your case, if s[index - 1] != ' ' is false, then s[index + 1212] != ' ' won't be evaluated at all, which in turn won't raise an error.