Andrew1024
Andrew1024

Reputation: 186

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.

Upvotes: 9

Views: 2049

Answers (3)

Clifford
Clifford

Reputation: 93476

Consider the following code:

i = 3

def test():
  global i ;
  i = i + 1
  return i

for x in range(0,test()):
  print( x, i )

Every time test() is callediis incremented, so the loop woul be endless iftest()` were evaluated on each iteration. The output however is :

0 4
1 4
2 4
3 4

Clearly therefore test() is evaluated once.

Upvotes: 0

Thierry Lathuille
Thierry Lathuille

Reputation: 24232

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.

Upvotes: 12

diya9000
diya9000

Reputation: 33

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.)

Upvotes: 1

Related Questions