Let's say you have some nested for-loop that you want to break out of from the inner loop:

x = default
for key, values in dict_of_sets: 
	for value in values: 
		if predicate(value): 
			x = key 
			break 2  # INVALID SYNTAX, SADLY...

Well, it turns out that Python supports for-else, so this can be made trivial:

x = default_value 
for key, values in dict_of_sets: 
	for value in values: 
		if predicate(key, value): 
			x = value 
			break  # THIS BREAKS BOTH LOOPS! 
	else: 
		continue 
	break

You don't need to know why this works to use it; but, if you do, here's how it works:

  • When the inner for-loop exhausts, its else-clause executes next, which continues the program through that iteration of the outer for-loop (quietly skipping the break statement on line 9).
  • If the inner for-loop is, instead, killed with the break on line 6, its else-clause is skipped, allowing the break statement on line 9 to execute and terminate the outer for-loop.

This can be used as much as you like:

for i in range(3): 
  for j in range(3): 
    for k in range(3): 
      for l in range(3): 
        for m in range(3): 
          for n in range(3): 
            print(i, j, k, l, m, n) 
            if input("Press enter to continue, or type anything to break out of all these loops.\n> "): 
              break  # THIS WILL BREAK ALL OF THE LOOPS! 
          else: 
            continue 
          break 
        else: 
          continue 
        break 
      else: 
        continue 
      break 
    else: 
      continue 
    break 
  else: 
    continue 
  break

 

Leave a Reply

Your email address will not be published. Required fields are marked *

Warning: This site uses Akismet to filter spam. Until or unless I can find a suitable replacement anti-spam solution, this means that (per their indemnification document) all commenters' IP addresses will be sent to Automattic, Inc., who may choose to share such with 3rd parties.
If this is unacceptable to you, I highly recommend using an anonymous proxy or public Wi-Fi connection when commenting.