Comment

Comment by xmcqdpt2

for/else is actually super useful for searching through a sequence or for iterating with a possible failure. Something like,

  for i in range(n):
      if search(i) == val:
          break
  else:
      raise KeyError("not found")
  found_index = i
It reduces the need for an additional flag. More importantly it makes it easier to ensure that the break condition is satisfied such that the loop variable can be used properly later on. Personally, I think an else condition should almost always be there for loops that gets broken early, similarly to always finishing if else chain with a final else.

ETA: Another pattern where it's really useful is to replace

  while True:
with a safer guaranteed terminating loop,

  for i in range(MAX_ITER):
     ...
  else:
    raise RuntimeError("exceeded max iterations")
parent xmcqdpt2 4 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton