In Python, are conditions in a loop re-evaluated before a new iteration is executed?

And*_*024 3 python for-loop list

As with regards to python, when it comes to a for loop, will it re-evaluate the upper bound before re-iteration?

Say I have the following scenario:

def remove(self,list,element):
     for x in range(0,len(list)):
           if somecondition:
               list.pop(x)
Run Code Online (Sandbox Code Playgroud)

Will the len(list) condition be re-evaluated before executing the next iteration of the for loop? (As done in some languages such as Objective-C I believe) As otherwise if a number of elements is popped, an out of bounds error would arise if say 1 element was removed, and the last iteration would try to access list[len(list)-1].

I've tried to investigate this myself however the results are muddled each time.

编辑:我相信我的问题不同于标记为重复的问题,因为我的问题是关于循环继续进行下一次迭代的条件,因此可以轻松地添加一个元素而不是删除一个元素。

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

Thi*_*lle 5

有关for语句的文档对此非常清楚:

for语句用于遍历序列的元素(例如字符串,元组或列表)或其他可迭代对象:

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

表达式列表被评估一次 ; 它应该产生一个可迭代的对象。为expression_list的结果创建一个迭代器。然后,按照迭代器返回的顺序,对迭代器提供的每个项目执行一次套件。

[强调我的]

因此,在您的情况下,range(0,len(list))只会被评估一次。