-1

I have the following code:

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
to_find = 5
found = False

for i in range(len(my_list)):
    found = my_list[i] == to_find
    if found:
        break

if found:
    print("Element found at index", i)
else:
    print("absent")

I am aware of the specific concept of using while or for loops in Python with a following else statement. So I understand that if I have a break statement and a following else statement that this is a specific Python implementation.

However, I think in my example this specific concept does not apply. Or?

I have a for loop where the index i runs from the beginning until the end. When the loop is finished (or breaks, doesn't matter as the if statement is executed anyway, it does not have to do anything with the for loop) the if statement is executed. Now, I do not understand why the if found: statement with the following print ("...", i) code does not throw an error.

I would have expected that the i is not known at the timepoint when the print statement is run. The i is the internal index variable in the for loop. So for me this is first of all not a "global" variable and second I would have not expected that the i is "saved". So it does contain the number of the last i it run through. I can see that clearly from the output code.

Why is i known at the time point when the print("Element found at index", i) is run? Or is it only know because my assumption is wrong and the break statement in the for loop does matter to be able to execute the following if statement without an error?

BertHobe
  • 217
  • 1
  • 14
  • You put a break statement, so `i` takes the last value of the for loop before break happens. Therefore, you get correct output. – PCM Sep 04 '21 at 08:32
  • `for` loops don’t introduce any new scope. – deceze Sep 04 '21 at 08:35
  • In Python, variables are scoped to functions, not smaller blocks like `for` loops. So `i` keeps its value after the loop is done. – Barmar Sep 04 '21 at 08:35

1 Answers1

0

The for loop doesn't have its one scope. The value of i is either the value when the loop was terminated or the last value generated by range.

Also, i is defined when you iterate over the loop.