October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk5 min

Write Once, Run Many: Understanding Python Loops

Python's for loop repeats over an iterable, while the while loop repeats while a condition holds. Here is how to choose between them, use range() and enumerate(), and predict break, continue, and loop else.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Python gives you two loop statements. A for loop repeats over the items of an iterable, and a while loop repeats as long as a condition stays true. Choosing between them comes down to one question: what decides whether the loop runs again? Once you can answer that, the rest of loop control (range(), enumerate(), break, continue, and the loop else clause) follows from the same idea.

Choose a loop by what controls repetition

The examples below follow the Python 3.14 documentation. The core behavior has been stable across Python 3 releases, but the reference pages are the authority if you are on an older interpreter.

A for statement works through the items an iterable supplies. Python evaluates the expression that produces the iterable once, creates an iterator from it, and on each pass assigns the next item to the loop target before running the indented suite. Strings, tuples, lists, and other iterables all work this way. The loop ends when the iterable is exhausted.

A while statement tests an expression before each pass and runs its suite while that expression is true. Use it when the decision to continue depends on a condition that can change inside the loop. You are responsible for making that condition eventually false, unless indefinite repetition is what you intend.

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

Side-by-side comparison

Question for while
What drives the next pass? The next item from an iterable A Boolean expression, retested before each pass
Typical use Processing each element of a collection, or a known sequence of numbers Waiting for a condition, repeating until a value meets a target, or input-driven loops
Ends when The iterable is exhausted The condition becomes false
Risk to watch Modifying the collection being iterated A condition that never changes, causing an endless loop

The distinction is about what determines the next pass, not merely a different spelling of a counted loop. If you find yourself writing a while loop only to increment a counter and compare it to a limit, a for loop over a range() usually reads better.

Looping over numbers with range()

range() produces an arithmetic progression of integers. Its stop value is excluded:

  • range(5) yields 0, 1, 2, 3, 4.
  • range(1, 6) yields 1 through 5.
  • range(0, 10, 3) yields 0, 3, 6, 9.

A range object supplies values as the loop asks for them. It does not build a list of every number first, so for n in range(1_000_000) does not allocate a million-element list. The official tutorial describes it as an iterable, which is why you can use it directly in a for statement.

Getting the index and the item together

Sometimes a task needs both the position and the value. The tutorial’s own question here is how to iterate over the indices of a sequence. Its answer is range() combined with len(), and then it notes that enumerate() is more convenient in most such cases. Use enumerate() when you need both, and loop directly over the sequence when you do not need indices:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
names = ["Ada", "Grace", "Linus"]
for index, name in enumerate(names):
    print(index, name)

Output:

0 Ada
1 Grace
2 Linus

Accumulating a result

When a loop builds a result, keep the changing state in a variable that exists before the loop starts, and update it on each pass:

total = 0
for number in range(1, 6):
    total += number
print(total)

This prints 15. The same pattern works with a while loop when the stopping point is not known in advance, for example summing values until the total passes a threshold:

total = 0
number = 1
while total < 20:
    total += number
    number += 1
print(total)

Here the loop stops when total reaches 21, the first running total that is at least 20. The condition is the thing that changes, so while is the natural fit.

Controlling a loop with break, continue, and else

break exits the nearest enclosing for or while loop immediately. continue skips the rest of the current pass and moves on to the next item, or to the next condition check in a while loop.

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

Both loop forms accept an else suite. It is easiest to read as “run this if the loop was not stopped by break.” It runs in two cases:

  • A for loop has exhausted its iterable.
  • A while loop ends because its condition became false.

It is skipped when break exits the loop. A return or an unhandled exception also leaves the loop without running it. Do not read loop else as an if–else pair; it has no condition of its own.

The tutorial demonstrates the most common use, searching for a value and reporting when nothing was found:

for n in range(2, 10):
    for factor in range(2, n):
        if n % factor == 0:
            print(n, "equals", factor, "*", n // factor)
            break
    else:
        print(n, "is a prime number")

Here the inner else runs only for values of n where the inner loop never hit break, meaning no factor was found.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Predicting what a loop will do

Trace the control flow in this order when you read an unfamiliar loop:

  1. Identify the controlling expression: an iterable for for, a Boolean expression for while.
  2. Check whether anything inside the suite changes that expression, or the collection being iterated.
  3. For each pass, note whether a continue skips the rest of the body.
  4. Note whether a break can exit the loop. If it can, the else suite will not run on that path.
  5. After the loop, remember that a for target keeps the last value it was assigned, and that an empty iterable never assigns it.

Changing a collection while looping over it

The tutorial warns that modifying a collection while iterating over that same collection can be tricky. This is a specific caution about changing the collection being iterated, and it does not mean every change inside a loop is unsafe. Two strategies avoid the problem: iterate over a copy of the collection, or build a new collection with the items you want.

numbers = [1, 2, 3, 4, 5, 6]
kept = []
for number in numbers:
    if number % 2 == 0:
        kept.append(number)
print(kept)

This prints [2, 4, 6]. Building a new list keeps the loop simple and makes the result explicit.

Assigning to the loop target inside the suite does not change which item the iterator supplies next. On each pass, the for statement assigns the next item from the iterator, regardless of what you did to the name in the previous pass.

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.

Further reading

The two primary references are the official tutorial chapter, More Control Flow Tools, and the language reference section on compound statements. The tutorial is the better starting point; the reference is the place to check exact behavior of condition testing and loop termination. A beginner Python book can also help with practice exercises, though none is required to learn loops from these references.

“

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
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver 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.