while loop
Loops while a condition is truthy. Use it when the number of iterations isn't known up front: BFS queues, stack processing, two pointers, binary search, and simulation loops.
Syntax
i = 0
while i < n:
...
i += 1
break and continue
while True:
x = next_value()
if x is None:
break # exit loop
if x < 0:
continue # skip to next iteration
process(x)
while-else (else runs only if the loop didn't break)
while i < n:
if nums[i] == target:
break
i += 1
else:
print("not found")
Process until empty: while queue:
from collections import deque
q = deque([start])
seen = {start}
while q: # BFS, O(V + E)
node = q.popleft()
for nei in graph[node]:
if nei not in seen:
seen.add(nei)
q.append(nei)
stack = [root]
while stack: # iterative DFS
node = stack.pop()
...
Two pointers
lo, hi = 0, len(nums) - 1
while lo < hi:
s = nums[lo] + nums[hi]
if s == target:
break
if s < target:
lo += 1
else:
hi -= 1
Binary search shape
def binary_search(nums: list[int], target: int) -> int:
lo, hi = 0, len(nums) - 1
while lo <= hi: # O(log n)
mid = (lo + hi) // 2
if nums[mid] == target:
return mid
if nums[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1 # lo is the insertion point here
binary_search([1, 3, 5, 7], 5) # -> 2
Loop with walrus
while (n := len(stack)) > 1:
...