Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk8 min

Loops in Python

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

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:

  • 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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

break: 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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Sale
ZUFECY 2-Pack Snake Climbing Rings, 3-Loop PP Enrichment Toy for Ball Python, Corn Snake, Lizard and Reptile Tank
  • 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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Performance and Memory Considerations

Loop performance depends heavily on how much work happens per iteration and whether you allocate large intermediate lists.

  • 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.Support on Ko-Fi

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 while loop, confirm the condition will eventually become false (e.g., decrementing n or moving to the next token).
  • If using while True, confirm there’s a reachable break.
  • Check for exceptions swallowed inside the loop (e.g., a bare except that 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).

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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 IndentationError or run the wrong code outside the loop.
  • Using while without state updates: conditions must change or the loop never ends.
  • Misusing break with loop-else: remember the loop-else else won’t run if break happens.
  • 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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

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

Bestseller No. 2
3M Belt Loop with D-ring 1500115, 5 lb Capacity
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
$11.59
Bestseller No. 5

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.