Python's loop else clause confuses everyone. Modifying a list while iterating crashes silently. range() is lazy. Let's find your gaps.
for and while loops have an else clause that runs only when the loop completes normally (without break). This is unique to Python and deeply useful — and deeply confusing the first time you see it.
for i in range(3): print(i) else: print("done")
for loops can have an else clause. It executes when the loop completes normally — i.e., it is NOT skipped by a break. Here the loop runs fully, so "done" prints. The else is misleadingly named — think of it as "no-break" instead.
for i in range(5): if i == 3: break else: print("no break") print("after loop")
break at i==3 exits the loop early, which skips the else clause entirely. So "no break" never prints. Only "after loop" prints (it's outside the loop). This is the primary use case for loop-else: searching for items — if found, break; the else means "item not found."
for i in range(0): # empty range print(i) else: print("else ran")
break). So the else clause runs. This surprises many people — an empty loop body still triggers the else.
i = 0 while i < 3: print(i) i += 1 else: print("while done")
while loops also support an else clause. It runs when the while condition becomes False naturally — not when a break exits the loop. Here, i reaches 3, condition fails, and the else runs.
for i in range(5): if i == 3: continue print(i)
continue skips the rest of the current iteration and moves to the next. When i == 3, the print(i) is skipped. Unlike break, continue does NOT exit the loop — it just moves to the next value.
r = range(10) print(type(r)) print(r[5]) print(len(r))
range() returns a range object — a lazy sequence. It does NOT store all values in memory. Despite this, it supports indexing (r[5]) and len() because range knows its start, stop, and step. This is more efficient than a list for large ranges.
print(list(range(1, 10, 3))) print(list(range(10, 0, -2))) print(list(range(5, 5))) # start == stop
range(start, stop, step): generates values from start up to (but not including) stop, stepping by step. With a negative step, it counts down. When start equals stop, the range is empty — no error, just an empty sequence.
for i in range(3): print(i) print(i) # after the loop
i is NOT scoped to the loop — it leaks into the enclosing scope and retains its last value after the loop ends. So after the loop, i == 2. This is different from C/Java where loop variables are scoped to the loop block.
nums = [1, 2, 3, 4, 5] for n in nums: if n % 2 == 0: nums.remove(n) print(nums)
[1, 3, 5] — but for tricky reasons.[1, 3, 5] in this specific case — but the approach is dangerously wrong in general. When you remove element at index 1 (value 2), element 3 slides to index 1. The iterator then moves to index 2, skipping 3. For even numbers in sequence, this "accidentally" works, but it will silently skip elements in many other cases.[x for x in nums if x % 2 != 0] — always iterate over a copy or use a comprehension.
nums = [1, 2, 3, 4] for n in nums[:] # iterate over a copy: if n % 2 == 0: nums.remove(n) print(nums)
nums[:] creates a full copy of the list. The loop iterates over the copy while nums.remove(n) modifies the original. This is safe and correct — all even numbers are removed. This is the standard idiom for mutating a list while iterating: iterate over a copy.
x = 10 result = "big" if x > 5 else "small" print(result) y = 3 print("odd" if y % 2 else "even")
value_if_true if condition else value_if_false. Note the condition is in the middle — the opposite of C's condition ? true : false. y % 2 = 1 when odd, which is truthy, so "odd" is returned.
x = 5 y = 10 if x > 3 else 20 if x > 1 else 30 print(y)
10 if (x > 3) else (20 if x > 1 else 30). Since x = 5 > 3 is True, the first condition wins and y = 10. The rest is not evaluated. Nested ternaries are valid Python but hard to read — use if/elif for clarity.
result = [x * 2 for x in range(5) if x % 2 == 0] print(result)
if x % 2 == 0 keeps 0, 2, 4), then applies the expression (x * 2 → 0, 4, 8). The order in the comprehension is: expression, for, if — but evaluation order is: for, if (filter), then expression.
x = 10 result = [x for x in range(3)] print(x) # what is x after the comprehension?
x inside the comprehension does NOT leak into the surrounding scope. So the outer x = 10 is unchanged. This is different from a regular for loop, where the variable leaks. In Python 2, comprehensions leaked — Python 3 fixed this.
for i in range(3): pass print("done", i)
pass is a no-op — it does nothing and allows the loop body to be syntactically non-empty. The loop still runs all 3 iterations. After the loop, i is 2 (loop variable leaks from regular for loops).
for i in range(3): for j in range(3): if j == 1: break print(i, j)
break only exits the innermost loop. The outer loop continues normally. For each value of i, the inner loop prints j=0 then breaks at j=1. Python has no labeled break (like Java's break label) — to break multiple loops, use a function and return, or a flag variable.
for i in [1, 2, 3]: if i == 2: continue print(i) else: print("else")
continue does NOT trigger the else to skip — only break does. continue just skips the current iteration. The loop still completes normally (all items are visited), so the else runs. Output: 1, then 2 is skipped, then 3, then "else".
items = ["a", "b", "c"] for i, v in enumerate(items, start=1): print(i, v)
enumerate(iterable, start=N) yields (index, value) pairs. The start parameter sets the starting index (default is 0). Here, start=1 makes the count start from 1 — great for human-readable numbered lists. Tuple unpacking for i, v in ... assigns each pair to two variables.