Python Random Fact: Never break in a while loop

Quiz

What do you think the following Python code outputs?

arr = [[1], [3], [5]]

while len(arr) > 0:
  inner_arr = arr.pop(0)
  for el in inner_arr:
    if el == 3:
      break
    print(el)

The answer is:

1
5

Did you expect the following output?

1

Why?

break only stops the inner for-loop, not the outer while-loop.

How to stop it?

arr = [[1], [3], [5]]

while len(arr) > 0:
  inner_arr = arr.pop(0)
  should_stop = False
  for el in inner_arr:
    if el == 3:
      should_stop = True
      break
    print(el)

  if should_stop:
    break

Conclusion

Be careful when using break in nested loops.