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.
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.
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
.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With