DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober 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 Scan×
Skip to content
World desk3 min

Python Loops: How to Use for, while, and range()

Python’s for loop processes iterable items, while repeats as long as a condition is true. Learn range(), enumerate(), dictionary loops, and loop control.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use a for loop when you want to process items from an iterable, such as a list or string. Use a while loop when repetition should continue as long as a condition is true. For numeric sequences, range() supplies the values for a for loop.

How a Python for loop works

A for loop takes items from an iterable one at a time, in order, and runs its indented body for each item. It is useful for lists, strings, dictionary views, and other iterable objects; it is not limited to counting numbers. Python’s control-flow tutorial and language reference describe this behavior.

As an Amazon Associate I earn from qualifying purchases.

words = ["loop", "through", "items"]

for word in words:
    print(word)

Here, word receives each string in turn, and print() runs once for each one. The indented lines form the loop body.

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

Use range() for a numeric sequence

When a task needs a progression of integers, use range(). Its stop value is excluded: range(5) produces 0, 1, 2, 3, and 4, so it represents five values rather than including 5.

for number in range(5):
    print(number)

You can also provide a start and a step. For example, range(2, 10, 2) produces 2, 4, 6, and 8. The start is included when it lies in the sequence; the stop is not.

If you only need each value in a sequence, iterate over the values directly. If you need both a sequence item and its index, enumerate() usually communicates that intent more clearly than combining range(len(items)) with indexing.

Choose between for and while

Loop Best suited to Normal stopping point
for Processing the items supplied by an iterable, or a numeric sequence from range(). The iterator has no more items.
while Repeating while a condition remains true, when the repetition is condition-driven rather than defined by a collection of items. The condition becomes false.

Either kind of loop can also end early with break. A while loop needs a path to stop: its body should update the condition or otherwise exit. If neither happens, the condition can remain true indefinitely. The official Python tutorial introduction demonstrates condition-driven repetition.

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.
remaining = 3

while remaining > 0:
    print(remaining)
    remaining -= 1

Each pass reduces remaining; the loop ends when it reaches zero.

Loop through indexes, dictionaries, or matching sequences

Python provides iterable-oriented patterns for common cases. The examples below follow the Python data-structures tutorial.

Get an index and its value with enumerate()

values = ["red", "green", "blue"]

for index, value in enumerate(values):
    print(index, value)

enumerate() yields an index and its corresponding item on each pass. By default, the index starts at zero.

Get dictionary keys and values with items()

settings = {"theme": "dark", "alerts": True}

for key, value in settings.items():
    print(key, value)

items() supplies each key-value pair, which can be unpacked into the loop variables.

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

Process corresponding items with zip()

questions = ["Name?", "Age?"]
answers = ["Mina", "28"]

for question, answer in zip(questions, answers):
    print(question, answer)

zip() pairs items by position. It stops when the shortest input iterable is exhausted.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Control a loop with break, continue, and else

  • break exits the nearest enclosing loop immediately.
  • continue skips the rest of the current pass and proceeds to the next one.
  • A loop’s optional else suite runs when the loop completes normally, but not when it ends through break.

The loop else is useful in a search: it can distinguish finding a match (and breaking) from checking every item without finding one.

numbers = [3, 7, 11]

for number in numbers:
    if number % 2 == 0:
        print("Found an even number")
        break
else:
    print("No even number found")

The else here belongs to the for loop, not to the if. It runs only if the loop exhausts numbers without executing break.

Avoid changing a collection while iterating over it

Adding to or removing items from a collection during traversal can change what the loop visits and lead to skipped or unexpected work. For filtering, build a separate result instead of altering the collection being traversed.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
users = {"Ari": "active", "Bo": "inactive", "Cam": "active"}
active_users = {}

for user, status in users.items():
    if status == "active":
        active_users[user] = status

This leaves users unchanged and puts the selected entries in active_users. If you need to delete entries from a list, iterate over a copy or create a new filtered list, as the Python control-flow tutorial advises.

Quick choice guide

  • Use for item in iterable: when the work is defined by the items to process.
  • Use for number in range(...): for a numeric progression; remember that the stop value is excluded.
  • Use enumerate(items) when you need both each item and its index.
  • Use while condition: when repetition depends on a condition, and make sure there is a way for it to become false or for the loop to exit.

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
Windows Errors? Fix Them Before They SpreadFree repair scan
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.