Selecting Between For and While Loops
Easy · Software Engineering Fundamentals · Software Engineer · Technical Screen
Prompt
Nearly every general-purpose programming language gives engineers both for loops and while loops. Although any computation written with one construct can be translated into the other, picking the wrong loop structure makes code harder to read and much easier to break.
Address the following four parts in your explanation:
- Core Intent & State Ownership: Contrast
forandwhileloops in terms of who manages loop setup, advancement, and stopping criteria. - Where
whileWins: Give at least one concrete engineering scenario where awhileloop is demonstrably safer or clearer than aforloop. - Where
forWins: Give a concrete scenario where aforloop is the stronger choice and explain which defects it prevents. - Non-Terminating Loops: Explain how accidental infinite loops arise in production code and how choosing
forversuswhilechanges your exposure to them.
To ground your comparison, implement and contrast both loop styles on this early-cutoff scan, where we collect API latency readings in order and stop immediately upon encountering the first reading strictly above sla_limit_ms:
latencies_ms = [18, 42, 75, 190, 240]
sla_limit_ms = 100
# Write this prefix scan with a `for` loop and with a `while` loop.
# Which version expresses the early-cutoff rule more cleanly, and what trade-offs appear?
Scope & Expectations
- Definite vs. indefinite iteration: Frame the distinction around known collections/counts versus open-ended state transitions rather than superficial syntax differences.
- Concrete bug mechanics: Point to specific failure modes—such as skipped elements during in-place deletion,
continuestatements bypassing manual counter increments, short-circuit ordering mistakes, or floating-point drift—using small, runnable examples. - Practical trade-offs on early exit: Compare compound
whileheaders againstforloops with guardbreakclauses across readability, index safety, and compatibility with lazy streams or iterators.
Step-by-step walkthrough
The fundamental difference: who owns loop progress?
Both
forandwhileloops can express any computation—a property called Turing completeness (meaning any repetition written with one loop can be mechanically rewritten with the other). In day-to-day software engineering, choosing between them is not about what the computer can run; it is about what promise the loop header makes to a human reader and which bugs become impossible to write.forloops express definite iteration (visiting items from a known collection, stream, or numeric range). The loop construct itself owns setup, stepping to the next item, and stopping at the end.whileloops express indefinite iteration (repeating an action as long as a boolean condition remains true, without knowing up front how many steps that will take). The loop header only checks the condition; your loop body is completely responsible for initializing state beforehand and advancing toward termination on every single branch.
Control part Python `for x in items:` Python `while condition:` ------------------ ------------------------------ ---------------------------------- 1. Initialization Automatic (`iter(items)`) Manual (`i = 0` before loop) 2. Stop condition Automatic (stops at end) Manual (`i < len(items)` in header) 3. Step / progress Automatic (fetches next `x`) Manual (`i += 1` on EVERY path!)Compare summing a list both ways:
latencies_ms = [18, 42, 75, 190, 240] # for loop: states "visit each reading"; zero index variables to mismanage. total_ms = 0 for reading in latencies_ms: total_ms += reading # while loop: forces manual index setup, bounds checking, and incrementing. total_ms = 0 i = 0 while i < len(latencies_ms): total_ms += latencies_ms[i] i += 1Implementing the early-cutoff scan both ways
Suppose
latencies_ms = [18, 42, 75, 190, 240]andsla_limit_ms = 100, and we want to collect readings in order until we hit the first value strictly above100(meaning18,42, and75are collected, and190triggers an early stop):latencies_ms = [18, 42, 75, 190, 240] sla_limit_ms = 100 # Approach A: for loop + early break within_sla_for = [] for reading in latencies_ms: if reading > sla_limit_ms: break within_sla_for.append(reading) # Approach B: while loop with compound condition in the header within_sla_while = [] i = 0 while i < len(latencies_ms) and latencies_ms[i] <= sla_limit_ms: within_sla_while.append(latencies_ms[i]) i += 1Trace both versions side by side on
[18, 42, 75, 190, 240]:Pass Index / Reading `while` header check `for` guard check within_sla ---- --------------- ------------------------------ -------------------- ------------ 1 i=0, reading=18 0 < 5 and 18 <= 100 -> True 18 > 100 -> False [18] 2 i=1, reading=42 1 < 5 and 42 <= 100 -> True 42 > 100 -> False [18, 42] 3 i=2, reading=75 2 < 5 and 75 <= 100 -> True 75 > 100 -> False [18, 42, 75] 4 i=3, reading=190 3 < 5 and 190 <= 100 -> False 190 > 100 -> break! [18, 42, 75] (stops)Which expresses the early-cutoff rule more cleanly?
- Why
whileappeals here: Puttingi < len(latencies_ms) and latencies_ms[i] <= sla_limit_msright in thewhileheader announces up front that this is not a full-list scan. However, it reintroduces manual indexingi += 1, only works on indexable sequences (failing on file streams or generators—on-demand iterators that yield one item at a time withoutlen()), and relies on short-circuit evaluation (evaluating left-to-right and stopping as soon as the outcome is decided): writinglatencies_ms[i] <= sla_limit_ms and i < len(latencies_ms)in reverse crashes withIndexErrorwhen every reading is<= sla_limit_ms! - Why
for+break(oritertools.takewhile) wins in Python:for reading in latencies_ms:with a top-of-loop guard clause (if reading > sla_limit_ms: break, an early check at the very start of a block) cannot go out of bounds, cannot forgeti += 1, and works on any iterable (any object you can loop over one element at a time). If you want the stopping rule right in the header without manual indices,itertools.takewhile(lambda x: x <= sla_limit_ms, latencies_ms)gives the best of both worlds.
- Why
When a `while` loop is objectively safer or clearer
Reach for
whilewhenever there is no fixed collection to traverse, or the work shrinks/grows dynamically during traversal:- Dynamic worklists (queues and stacks): In breadth-first search (BFS) (exploring a graph layer by layer using a first-in, first-out queue), discovering new neighbors appends items to the queue while the loop pops from the front.
while queue:states the exact mathematical truth—keep working until no pending nodes remain:
```python from collections import deque
graph = {"start": ["mid_a", "mid_b"], "mid_a": ["goal"], "mid_b": ["goal"], "goal": []} visited = {"start"} queue = deque(["start"]) visit_order = []
while queue: node = queue.popleft() visit_order.append(node) for neighbor in graph[node]: if neighbor not in visited: visited.add(neighbor) queue.append(neighbor) # visit_order == ["start", "mid_a", "mid_b", "goal"] ```
- In-place removal from a list: Mutating a collection inside a
forloop over that same collection is a classic bug. Modifying a Pythondictorsetmid-forraisesRuntimeError, and callingnums.remove(x)insidefor x in nums:silently skips elements because later items slide left into the slot theforiterator just stepped past!
text Buggy `for x in [1, 2, 2, 3]:` removing 2s: step 0 (slot 0 -> 1): keep -> [1, 2, 2, 3] step 1 (slot 1 -> 2): remove! Second 2 slides left into slot 1 -> [1, 2, 3] step 2 (slot 2 -> 3): iterator moves to slot 2, SKIPPING the second 2!When you cannot simply build a new list (`[x for x in nums if x != 2]`) and must delete in place, a `while` loop is objectively safer because it only increments `i` when **nothing** slid into slot `i`:python nums = [1, 2, 2, 3] i = 0 while i < len(nums): if nums[i] == 2: nums.pop(i) # next element shifted into index i; re-check index i! else: i += 1 # nums == [1, 3]- Convergence, numeric state, and sentinel streams: Algorithms like binary search (
while lo <= hi:), Euclid's greatest common divisor (while b != 0: a, b = b, a % b, shrinking(48, 18) -> (18, 12) -> (12, 6) -> (6, 0)in 3 steps), or reading commands until a sentinel value (a special stop marker like"quit"or empty socket bytesb"") have no predetermined count. Note that stream loops should always pass a default tonext(..., "quit")so premature end-of-input stops cleanly instead of raisingStopIteration:
python stream = iter(["move", "jump", "quit", "ignored"]) handled = [] command = next(stream, "quit") while command != "quit": handled.append(command) command = next(stream, "quit") # handled == ["move", "jump"]- Dynamic worklists (queues and stacks): In breadth-first search (BFS) (exploring a graph layer by layer using a first-in, first-out queue), discovering new neighbors appends items to the queue while the loop pops from the front.
When a `for` loop is preferred
Prefer
forwhenever the set of elements or maximum step count is known before iteration starts—traversing lists, dictionaries, file lines,range(n), or bounded retries (for attempt in range(3):). Because the language runtime advances the iterator automatically at the end of every pass,foreliminates three pervasive manual-whiledefects at once:readings = [18, 25, 42] # Defect 1 (Off-by-one): `while i <= len(readings)` reads readings[3] -> IndexError. # Defect 2 (Forgotten step): omitting `i += 1` freezes i at 0 forever. # Defect 3 (`continue` trap): jumping back to `while` BEFORE `i += 1` hangs on 25! # i = 0 # while i < len(readings): # if readings[i] % 2 == 1: # continue # BUG: skips i += 1, stuck at i = 1 forever! # i += 1 # Safe `for` equivalent: `continue` still advances cleanly to 42 on the next pass. even_readings = [] for reading in readings: if reading % 2 == 1: continue even_readings.append(reading)Even when you need positions or parallel traversal,
enumerate(items)andzip(names, scores)preserve the safety offorwithout manual index arithmetic.Infinite loops and how loop choice shifts the risk
An infinite loop occurs whenever the termination condition never evaluates to
Falseand nobreak/returnexecutes. Four mechanisms cause almost all accidental infinite loops in production:- Missing or bypassed state updates in
while: Forgettingi += 1, updating the wrong variable in nested loops (i += 1instead ofj += 1), or hitting acontinuebefore the update line. - Moving away from the boundary or integer wraparound: Decrementing
i -= 1while checkingi < n, or writingfor (unsigned int i = n - 1; i >= 0; i--)in C/C++, where unsigned0 - 1wraps around to4,294,967,295(>= 0forever!). - Exact floating-point equality checks: Base-2 floats cannot represent
0.1exactly, so repeated addition drifts past1.0without ever equaling1.0:
text Start x = 0.0, add 0.1 each step: after 9 steps: x = 0.8999999999999999 (x != 1.0 is True, x < 1.0 is True) after 10 steps: x = 0.9999999999999999 (x != 1.0 is True! x < 1.0 runs an 11th time!) after 11 steps: x = 1.0999999999999999 (`while x != 1.0:` NEVER terminates!)Always iterate over integer counts (`for step in range(10): x = step * 0.1`) and use `<=` / `<` tolerances rather than `!=` on floats.- Unbounded
foriterables: While aforloop over an unmodified finite tuple orrange(n)cannot loop infinitely,for x in items: items.append(x)orfor n in itertools.count():without abreakwill still run forever!
To verify any
whileloop terminates, state its loop variant (a non-negative integer quantity—likehi - loin binary search orbin Euclid's algorithm—that strictly decreases on every branch of the body). And for intentionally long-running loops (game frame loops or network accept loops), writewhile running:orwhile True:with an explicit shutdown check, and cap retry/polling loops with a max-attemptfor attempt in range(MAX_TRIES):or wall-clock deadline.- Missing or bypassed state updates in
Quick decision checklist
Situation Best choice -------------------------------------------------------- ------------------------------------ Visit every item in a collection, file, or range `for item in collection:` Need index or parallel sequences too `for i, x in enumerate(...)` / `zip` Stop early at a threshold on any iterable `for` + guard `break` (or `takewhile`) Retry a flaky call safely `for attempt in range(MAX_RETRIES):` Process a queue/stack that grows and shrinks (BFS/DFS) `while worklist:` Delete elements in place where indices shift `while i < len(items):` (or rebuild) Converge a numeric interval / stream until sentinel `while` + explicit progress check Server event loop or game frame loop `while running:` + clear exit path
Intuition & how it works
Think of a for loop as riding a commuter train along a fixed line of stations, and a while loop as driving a car down the highway until you spot a specific landmark. On the train (definite iteration, looping over a known collection or range), the conductor handles starting, advancing from station to station, and stopping at the end of the line—all you do is act at each stop. In the car (indefinite iteration, repeating until a condition changes), you only have a rule for when to keep driving, so you are personally responsible for steering forward and watching for the exit.
Saying "both are equivalent because of Turing completeness (any loop written with one construct can be rewritten with the other), so either is fine" misses why bugs happen in real code. Using a manual while loop to walk a plain list forces you to write index setup, bounds checks, and i += 1 by hand—inviting off-by-one crashes and infinite hangs whenever an early continue jumps over i += 1. Conversely, forcing a for loop onto a mutating list or a dynamically growing search queue either raises a runtime error, silently skips shifted elements, or requires awkward dummy ranges.
Walk through the latency-cutoff scan—latencies_ms = [18, 42, 75, 190, 240] with sla_limit_ms = 100—to compare how both loops stop early:
- Readings 0–2 (
18,42,75): Bothfor reading in latencies_ms:(checkingif reading > 100: break) andwhile i < len(latencies_ms) and latencies_ms[i] <= 100:accept each value in turn (within_sla = [18, 42, 75]). - Reading 3 (
190): Infor, the guard clause (a top-of-block exit check) sees190 > 100and executesbreak; inwhile,latencies_ms[3] <= 100evaluates toFalseand exits the header cleanly without ever touching240. - Comparing the trade-off: The
whileheader puts the full stop condition in one place (relying on short-circuit evaluation—checkingi < len(latencies_ms)before indexinglatencies_ms[i]), whereasfor+breakavoids manual indexing altogether and works on any iterable (including streams and generators that produce items lazily withoutlen()).
Key points
forvs.whileintent:fornames what collection or count you will traverse and owns loop advancement;whilenames what condition keeps you going and delegates progress to the loop body.- When
whileis safer or clearer: Dynamic worklists like breadth-first search (while queue:popping nodes while appending newly discovered neighbors), in-place list deletion where elements shift left (nums.pop(i)without incrementingi), numeric convergence (lo <= hiin binary search,b != 0in Euclid's GCD), and reading streams up to a sentinel value (a stop token like"quit"orb"", using a safe EOF default likenext(stream, "quit")). - When
foris preferred: Traversing existing collections, ranges, dictionaries, or files, usingenumerate/zipwhen indices or paired lists are needed, and capping retries (for attempt in range(5):) so failures cannot spin forever. - Root causes of infinite loops: Missing
i += 1or skipping it viacontinueinsidewhile, moving the counter in the wrong direction (or unsigned integer underflow in C/C++), testing floating-point equality (0.1added 10 times is0.9999999999999999, sowhile x != 1.0:never ends), and appending to a list while iterating over it infor. - Proving termination: Every
whileloop should have a clear loop variant (a non-negative integer measure, likehi - loor queue work remaining, that strictly shrinks on every execution path) or an explicit attempt/timeout cap when waiting on external I/O.
Common mistakes
- Dismissing the choice as purely stylistic: Turing equivalence means both compute the same functions, not that both protect equally against off-by-one and infinite-loop bugs.
- Reversing the
whilebounds check (latencies_ms[i] <= sla_limit_ms and i < len(latencies_ms)): Without checkingi < len(latencies_ms)first, short-circuitandindexeslatencies_ms[len(latencies_ms)]and crashes withIndexErrorwhen all readings sit within the limit. - Placing
continuebeforei += 1in awhileloop: That branch jumps straight back to thewhilecondition with the exact samei, freezing the program in an infinite loop. - Removing items inside
for x in my_list:: Deleting at indexishifts indexi + 1down into sloti, while theforiterator still advances toi + 1—silently skipping the adjacent element ([1, 2, 2, 3]leaves[1, 2, 3]). - Using floating-point
!=or==as a loop stop condition: Binary rounding error makes exact hits unreliable; iterate over an integer step counter instead. - Claiming
forloops can never be infinite: Iterating over an infinite generator (itertools.count()) or appending to the list being traversed (for x in a: a.append(x)) runs until memory runs out.
Follow-up questions
- How do declarative collection pipelines such as
map,filter, andforEachshift the trade-offs around choosing an explicit loop? Declarative helpers (and Python list/generator comprehensions) shift focus from how to step to what data transformation is happening—maptransforms 1-to-1,filterselects a subset, and neither exposes a mutable index or infinite-loop risk. However, they trade away control-flow flexibility: JavaScript'sArray.forEachcannotbreakearly orawaitsequentially (usefor...of,some, orfindinstead), and Python 3'smap/filterreturn lazy iterators (computing values only when consumed, so side effects inside an unconsumedmap(...)never run at all). - When a language offers
for-eachtraversal over collections, in what situations do you still need an explicit index-drivenforloop? Whenever an element's position or relationship to other indices is part of the logic, such as comparing neighbors (arr[i]vs.arr[i + 1]), mutating array slots in place (arr[i] *= 2), striding by2, or iterating backward fromlen(arr) - 1down to0so in-place deletions do not shift unvisited indices. In Python,enumerate,zip, slicing, andreversedhandle many of these cleanly, whereas in languages like Java or Go an index loop (orIterator.remove()/removeIf) avoidsConcurrentModificationExceptionand slice-copy overhead. - When do
breakandcontinuestatements make a loop cleaner to read, and when do they become a maintainability hazard? A singlecontinueorbreaknear the top of a loop acts as a clean guard clause—flattening nestedif/elsepyramids and stating early-skip or early-found conditions right away without extra boolean flags likefound = False. Readability suffers when multiplebreakandcontinuejumps are buried deep inside a 50-line loop body (making control flow resemblegotospaghetti, and risking skipped updates inwhileloops); at that point, extracting the loop body into a small helper function with namedreturnvalues makes every exit self-documenting.
Follow-up questions
- How do declarative collection pipelines such as `map`, `filter`, and `forEach` shift the trade-offs around choosing an explicit loop?
- When a language offers `for-each` traversal over collections, in what situations do you still need an explicit index-driven `for` loop?
- When do `break` and `continue` statements make a loop cleaner to read, and when do they become a maintainability hazard?
Similar questions
- JavaScript IEEE-754 Numeric Validation Utilities
- End-to-End Browser Lifecycle of a Web Page Load
- Owning and Resolving a User-Visible Incident
- Tally Tagged Numeric Segments Alphabetically
- Navigating a Challenging Engineering Project
- Resolving an Engineering Design Disagreement
More Riotgames interview questions
- Owning and Resolving a User-Visible Incident Easy
- Tally Tagged Numeric Segments Alphabetically Easy
- Navigating a Challenging Engineering Project Easy Pro
- JavaScript IEEE-754 Numeric Validation Utilities Easy Pro
- Resolving an Engineering Design Disagreement Easy Pro
- End-to-End Browser Lifecycle of a Web Page Load Easy Pro