break — Advanced Examples
Exits the nearest enclosing for or while loop immediately
Break in complex iteration patterns
Using break with itertools and generators.
python
import itertools # Break with itertools.count (infinite iterator) for i in itertools.count(1): if i * i > 100: print(f"First square > 100: {i}^2 = {i*i}") break # Using break to implement takewhile manually def take_until(predicate, iterable): result = [] for item in iterable: if predicate(item): break result.append(item) return result data = [2, 4, 6, 7, 8, 10] evens = take_until(lambda x: x % 2 != 0, data) print(f"Evens before first odd: {evens}") # Break with walrus operator nums = iter([3, 1, 4, 1, 5, 0, 2, 6]) while (n := next(nums, None)) is not None: if n == 0: print("Hit zero, stopping") break print(n, end=" ") print()
Expected Output
First square > 100: 11^2 = 121 Evens before first odd: [2, 4, 6] 3 1 4 1 5 Hit zero, stopping
break works with any loop, including those over infinite iterators. Combined with walrus operator, it enables clean sentinel-based loops.
Want to try these examples interactively?
Open Advanced Playground