Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)

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.

Edit: I believe that my question is different to the one flagged as a duplicate, as my question is regarding the condition for the loop to continue to the next iteration, it could easily ba adding an element instead of removing an element.

For clarification, my question asks whether or not the for loop condition will recheck the conditions posed before the next iteration.

like image 872
Andrew1024 Avatar asked Jan 26 '23 14:01

Andrew1024


2 Answers

The documentation about The for statement is clear about this:

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.

[emphasis mine]

So, in your case, range(0,len(list)) will only be evaluated once.

like image 87
Thierry Lathuille Avatar answered May 25 '23 04:05

Thierry Lathuille


Yes, you can see an out of range error if you try the following:

my_list = [0,1,2,3,4,5]
for x in range(0, len(my_list)):
    print("Length of my_list:", len(my_list))
    my_list.pop(x)

(You should also avoid using a variable name like list as it will shadow Python's built in list.)

like image 25
diya9000 Avatar answered May 25 '23 04:05

diya9000