在Python中,是否在执行新迭代之前重新评估循环中的条件?

至于
python,当涉及到for循环时,它会在重新迭代之前重新计算上限吗?

说我有以下情况:

def remove(self,list,element):
     for x in range(0,len(list)):
           if somecondition:
               list.pop(x)

在执行for循环的下一次迭代之前,是否会重新评估len(list)条件? (正如在某些语言中所做的那样,例如Objective-C我相信)如果弹出了许多元素,如果说删除1个元素,则会出现越界错误,最后一次迭代会尝试访问列表[len(列表)-1].

我自己试图对此进行调查,但每次结果都很混乱.

编辑:我认为我的问题与标记为重复的问题不同,因为我的问题是关于循环继续下一次迭代的条件,它可以很容易地添加元素而不是删除元素.

为了澄清,我的问题是询问for循环条件是否会重新检查下一次迭代之前提出的条件.

最佳答案 关于
The for statement的文档很清楚:

The for statement is used to iterate over the elements of a sequence (such as a string, tuple or list) or other
iterable object:

for_stmt ::= “for” target_list “in” expression_list “:” suite
[“else” “:” suite]

The expression list is evaluated once; it should yield an iterable object. An iterator is created for
the result of the expression_list. The suite is then executed once for
each item provided by the iterator, in the order returned by the
iterator.

[强调我的]

因此,在您的情况下,范围(0,len(列表))将仅评估一次.

点赞