break
break ends the loop it is directly inside — only that one. Code after it in the body, the remaining iterations and the loop’s else block are all skipped.
for x in items: if found(x): break
for x in items: if found(x): break else: not_found()
for row in grid: for cell in row: if cell: break # inner only
Demo
seen = [] for n in [3, 5, -1, 8]: if n < 0: break seen.append(n) seen
In the break tab, everything from the first negative on is missing — the negative itself too, because break comes before append. In the break skips else tab, "else" appears only when no break happened, which includes the empty list. In the nested loops tab, every row i = 0, 1, 2 shows up: break stopped the inner j loop each time, never the outer one.
Syntax slots
| Name | Type | Required | Description |
|---|---|---|---|
| (none) | statement | no | break takes no operand and no label. It must be inside the body of a for or while loop (not in a nested def or class). |
Common patterns
def find_admin(users): for user in users: if user.is_admin: break else: return None return user
def ask_number(prompt): while True: text = input(prompt) if text.isdigit(): break print("digits only") return int(text)
def find(grid, target): for r, row in enumerate(grid): for c, cell in enumerate(row): if cell == target: return r, c return None
def first_negative(nums): return next((n for n in nums if n < 0), None)
Examples
Pitfalls
hits = [] for i in range(3): for j in range(3): if i + j == 1: hits.append((i, j)) break hits
def first_hit(): for i in range(3): for j in range(3): if i + j == 1: return (i, j) first_hit()
compile('for x in y:\n def cb():\n break', '<demo>', 'exec')
def cb(x): return x > 1 for x in [1, 2, 3]: if cb(x): break x
log = [] for cmd in ['go', 'stop', 'go']: match cmd: case 'go': log.append('moving') break case 'stop': log.append('halt') log
log = [] for cmd in ['go', 'stop', 'go']: match cmd: case 'go': log.append('moving') case 'stop': log.append('halt') log
When to use
- Stopping a search at the first match
- Leaving a while True loop when its work is done
- Bailing out of a loop on an error condition you handle right after it
- Leaving several nested loops → return from a function
- Skipping one item and carrying on → continue
- A search that just returns the match → next(generator, default) or any()
Notes
FAQ
There is no labelled break. The cleanest way is to move the loops into a function and return. Alternatives: set a flag and check it after the inner loop, use for / else on the inner loop with continue / break, or flatten the loops with itertools.product so a single break is enough.