Loops are one of the core ways Python programs “do the same work repeatedly” — iterating over data, repeating until a condition flips, and transforming collections.
If you can write correct, readable loops, you’ll be able to handle most real-world tasks: parsing logs, processing files, aggregating stats, and building data pipelines.
As an Amazon Associate I earn from qualifying purchases.
This guide covers Python loops end-to-end: syntax, patterns, edge cases, loop-else, comprehensions, and the mistakes that cause infinite loops or off-by-one bugs.
The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →What Are Loops in Python and Why They Matter
In Python, loops let you execute a block of code multiple times. Two primary loop types cover most use cases:
#1 Best Overall
- for: iterate over items in an iterable (list, tuple, string, dict, range, custom iterables).
- while: repeat while a condition remains true.
Python emphasizes clarity: loop variables are local to the loop, indentation controls scope, and built-ins like enumerate() and zip() reduce boilerplate.
Loop Basics: Syntax and Execution Model
Python uses indentation to define the loop body. A loop header ends with a colon (:), and the next indented block runs each iteration.
for loop skeleton
for item in iterable: # loop body ...
while loop skeleton
while condition: # loop body ...
Two details matter in practice: (1) the iterable/condition must be correct, and (2) your loop body must not accidentally prevent progress (e.g., failing to update a variable in a while loop).
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
The for Loop: Iterate Over Items
The for loop walks through each element produced by an iterable. This is Python’s most common iteration tool.
Basic example
names = ["Ada", "Grace", "Linus"]
for name in names: print(name)
The loop variable (name) takes each element in turn. The iterable can be any object implementing the iteration protocol.
for with range()
Use range() when you need counting (or indexes). Examples below show common boundaries.
for i in range(5): print(i) # 0..4
range(stop) produces values from 0 up to (but not including) stop.
Recommended Free Tools
The while Loop: Repeat Until a Condition Changes
A while loop keeps running as long as its condition evaluates to true. Unlike for, Python does not automatically advance an index for you—your loop body must ensure the condition eventually becomes false.
Countdown example
n = 5
while n > 0: print(n) n -= 1
If n never changes, you’ll get an infinite loop.
Looping over user input
total = 0
while True: s = input("Enter a number (or blank to finish): ").strip() if s == "": break total += float(s)
Rank #2
3M Belt Loop with D-ring 1500115, 5 lb Capacity
- Belt Loop D-rings are compatible with 3M DBI-SALA Comfort and Utility tool belts
- Fast, simple and effective means to tie-off your tools to one of our 3M DBI-SALA belts
- Belt loop D-ring, 5 lb (23 kg) capacity
- For industrial/occupational use only. Not for consumer sale or use
print("Total:", total)
This pattern uses while True plus a break when the exit condition is met.
Control Flow Inside Loops: break, continue, and pass
Python provides loop control statements that affect how iterations proceed.
Do these 3 things before closing this tab:
1Scan for outdated or missing drivers - takes under a minute2Clear out junk files and repair common Windows errors3Fix the driver behind crashes, sound loss and screen glitchesbreak: exit the loop immediately
for x in [10, 9, 7, 2, 1]: if x < 5: print("Found:", x) break
break stops the loop and continues execution after the loop block.
continue: skip to the next iteration
for x in range(6): if x % 2 == 0: continue print(x) # prints 1, 3, 5
continue skips the remaining body for the current iteration.
pass: do nothing (useful as a placeholder)
while condition: pass # placeholder; replace with real logic
Be careful: pass doesn’t change state, so this often becomes an infinite loop if condition never becomes false.
Using loop-else: When a for/while Finishes Without break
Python supports an else clause on loops. The else block runs only if the loop terminates normally—meaning it wasn’t stopped by break.
Free tools Windows power users keep installed
One-click scans. No signup required.
for-else example
items = ["cat", "dog", "bird"]
needle = "hamster"
for item in items: if item == needle: print("Found") break
else: print("Not found") # runs because no break occurred
while-else example
n = 10
while n > 0: n -= 1 if n == 7: break
else: print("Completed without break")
Here, while exits due to break, so the else does not run.
Common Iteration Patterns
Most “real” loop code relies on a handful of iteration helpers. Learning these saves time and reduces bugs.
Iterate with range()
Use range() for counting and integer sequences. Its signature is range(stop), range(start, stop), or range(start, stop, step).
# start..stop-1
for i in range(2, 6): print(i) # 2, 3, 4, 5
# step can be negative
for i in range(10, 0, -2): print(i) # 10, 8, 6, 4, 2
Iterate with enumerate()
enumerate() yields index + value pairs, which avoids manually tracking an index variable.
letters = ["a", "b", "c"]
for i, ch in enumerate(letters): print(i, ch)
Iterate with zip()
zip() groups elements from multiple iterables. It stops at the shortest input length.
Quick wins for a faster PC:
Scan for outdated or missing drivers - takes under a minuteDriver Scan →Repair Windows errors before they cause bigger problemsFix Now →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →a = [1, 2, 3]
b = ["x", "y"]
for left, right in zip(a, b): print(left, right) # (1,x), (2,y)
If you need to keep all items, consider padding (custom logic) or itertools.zip_longest.
Iterate over dicts, keys, values, and items()
Dict iteration defaults to keys in insertion order. Use explicit views when you need values or key/value pairs.
user = {"name": "Ada", "role": "engineer"}
for k in user: # keys print(k)
for v in user.values(): # values print(v)
for k, v in user.items(): print(k, v)
Use sorted() during iteration
When order matters, wrap the iterable with sorted(). For dicts, sorted(user) sorts keys.
Rank #4
- Includes two snake climbing rings, giving your reptile more enrichment options and allowing for easy rotation or placement in multiple tanks.
- 3-LOOP DESIGN: Each ring features three loops to encourage natural climbing behavior, providing physical activity and mental stimulation for your reptile.
- WIDE COMPATIBILITY: Suitable for ball pythons, corn snakes, lizards, and a variety of other reptiles, making it a versatile addition to any reptile habitat.
- DURABLE PP MATERIAL: Constructed from polypropylene (PP), these climbing rings are sturdy, lightweight, and built to withstand regular use inside a reptile tank.
- ENRICHMENT TOY: Promotes natural instincts by giving snakes and lizards a structure to explore, climb, and coil around, helping to keep them active and engaged.
scores = {"tom": 8, "ana": 10, "bob": 7}
for name in sorted(scores): print(name, scores[name])
For sorting by value, sort scores.items() with a key.
for name, score in sorted(scores.items(), key=lambda kv: kv[1]): print(name, score)
Looping Over Strings, Lists, and Custom Iterables
You can loop over strings like sequences of characters, lists like collections of elements, and any custom object that defines iteration.
Strings
s = "python"
for ch in s: print(ch)
Note that iterating over Unicode text can be tricky when you care about grapheme clusters (user-perceived characters). Most scripts are fine for character-level iteration, but emojis and combined characters may require additional handling.
Custom iterables
To make an object work with for, implement __iter__ returning an iterator, or implement __getitem__ with sequential indexes (older pattern; __iter__ is preferred).
class Counter: def __init__(self, n): self.n = n def __iter__(self): current = 1 while current <= self.n: yield current current += 1
for x in Counter(3): print(x) # 1, 2, 3
Comprehensions as Loop Alternatives
List/set/dict comprehensions often replace simple loops with more compact expressions. They’re not always faster, but they can be cleaner for transformations.
List comprehensions
nums = [1, 2, 3, 4]
squares = [n * n for n in nums]
print(squares) # [1, 4, 9, 16]
You can include conditions:
evens = [n for n in nums if n % 2 == 0]
print(evens) # [2, 4]
Set and dict comprehensions
unique_lengths = {len(w) for w in ["a", "to", "cat"]}
print(unique_lengths) # {1, 2, 3}
mapping = {"k" + str(i): i for i in range(3)}
print(mapping) # {"k0": 0, "k1": 1, "k2": 2}
Generator expressions
Generator expressions produce values lazily, which is helpful for large inputs.
nums = range(10_000_000)
count_even = sum(1 for n in nums if n % 2 == 0)
print(count_even)
This uses a generator expression (inside sum) instead of building a huge list first.
Windows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallCrashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minutePerformance and Memory Considerations
Loop performance depends heavily on how much work happens per iteration and whether you allocate large intermediate lists.
Best Value
- Avoid building big lists when you can stream: prefer generator expressions or iterators.
- Prefer built-ins for reductions/aggregations:
sum(),any(),all(),min(),max(). - Don’t over-nest: deeply nested loops can explode runtime (O(n²), O(n³), etc.).
When performance matters, measure. A loop that looks “inefficient” can still be fine for small datasets, while a “clean” comprehensions approach may allocate large structures.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Debugging and Troubleshooting Loop Issues
When a loop misbehaves, the fix usually comes down to a wrong condition, wrong boundary, or a missing state update.
Infinite loop: what to check
- In a
whileloop, confirm the condition will eventually become false (e.g., decrementingnor moving to the next token). - If using
while True, confirm there’s a reachablebreak. - Check for exceptions swallowed inside the loop (e.g., a bare
exceptthat skips the state update).
Off-by-one errors with range()
range is “stop-exclusive.” If you expect the number 5 to appear, you likely need range(6), not range(5).
list(range(5)) # 0,1,2,3,4
list(range(6)) # 0,1,2,3,4,5
Wrong zip alignment
zip() truncates at the shortest iterable. If you silently lose data, that’s why. Validate lengths before zipping, or use itertools.zip_longest for padding.
Modifying a list while iterating
Modifying the same list you’re iterating over can skip items or cause unpredictable behavior.
nums = [1, 2, 3, 4]
for x in nums: if x == 2: nums.remove(x)
# This can skip items because indices shift.
Better approaches include iterating over a copy (for x in nums[:]), building a filtered list, or using list comprehension.
Common Mistakes to Avoid
- Forgetting indentation: Python will raise
IndentationErroror run the wrong code outside the loop. - Using
whilewithout state updates: conditions must change or the loop never ends. - Misusing
breakwith loop-else: remember the loop-elseelsewon’t run ifbreakhappens. - Shadowing built-ins: avoid variables named
list,dict,str, etc. - Choosing loops where comprehensions fit badly: comprehensions are best for simple transformations and filters; use loops for multi-step logic.
Python Loop Cheatsheet
| Goal | Recommended construct | Example |
|---|---|---|
| Iterate items | for |
for x in items: |
| Repeat until condition changes | while |
while n > 0: |
| Exit early | break |
if cond: break |
| Skip current iteration | continue |
if bad: continue |
| Run code only if no break occurs | for/while ... else |
for ...: ... else: ... |
| Index + value | enumerate() |
for i, x in enumerate(a): |
| Parallel iteration | zip() |
for a, b in zip(x, y): |
| Filter/transform | Comprehension | [f(x) for x in xs if ok] |
| Stream values | Generator expression | sum(1 for x in xs if ok) |
Bottom Line
Use for when you’re iterating over data and while when you need a condition-driven loop that you update yourself. Add break, continue, and loop-else only when they make the intent clearer, not when they obscure it.
If you remember one rule: in a while loop, the condition must move toward failure; in a for loop, the iterable must actually produce the elements you expect.
FAQs
Do loops in Python have scope?
Yes. Loop variables are scoped to the surrounding function/module, not inside the loop body. For example, after for x in ..., x is still accessible outside the loop (inside the same function).
Is loop-else commonly used?
It’s uncommon, but it’s useful and correct for “search” patterns. If you find yourself using a flag variable like found = False, for/while ... else can replace it with cleaner logic.
What’s the difference between break and return in a loop?
break exits only the loop and continues after it. return exits the entire function (or method) immediately, skipping any remaining code.
Quick wins for a faster PC:
Repair Windows errors before they cause bigger problemsFix Now →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Why does my program skip items when removing from a list?
Because indices shift when you remove elements while iterating. Build a new list with a comprehension, iterate over a copy, or use an index-based approach if you must.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.




