Free tools Windows power users keep installed
One-click scans. No signup required.
Use a for loop with range(n) to run a block a fixed number of times, a while loop when repetition depends on a condition, and sequence or itertools tools when you need to repeat values rather than execute statements. The right choice depends on what repeats and how it should stop.
Repeat a block of code a fixed number of times
Use for _ in range(n): when you know how many times to run a block. The underscore is a conventional name for a loop variable you do not need. Indent the statements to repeat beneath the loop:
for _ in range(4):
print("Hello")
range(4) yields four integers: 0, 1, 2, and 3. Its endpoint is excluded, so range(n) yields n values when n is a positive integer. A range produces values as needed rather than building a list of them. See the Python Tutorial’s explanation of for loops and range.
If the block needs the current count, use a named variable instead of an underscore:
The Tool Desk
Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →#1 Best Overall
for attempt in range(3):
print("Attempt", attempt + 1)
Python’s for loop is not limited to counting. When processing existing items, iterate over the items directly rather than using an index range:
for name in ["Ada", "Grace", "Guido"]:
print(name)
Repeat code until a condition changes
Use while condition: when you cannot know the number of repetitions in advance and want the loop to continue as long as a condition is true. Make sure the body changes something that can eventually make the condition false, or exit deliberately with break.
remaining = 3
while remaining > 0:
print("Still working")
remaining -= 1
Without a change to remaining (or another way out), this loop would run indefinitely. Use break when a specific event should end a loop early; it works in both for and while loops. The Python Tutorial’s control-flow guide also documents continue for skipping to the next iteration.
Rank #2
Call a function repeatedly
Put a function call inside a loop. If the function should receive different arguments each time, iterate over those inputs:
def greet(name):
print(f"Hello, {name}")
for name in ["Ada", "Grace", "Guido"]:
greet(name)
For some iterator-based workflows, map(function, iterable) applies a function to successive input values. For a function that takes multiple arguments, itertools.starmap(function, iterable_of_argument_tuples) unpacks each tuple into a call. Use a regular loop when it makes the operation clearer or when you need straightforward control over side effects.
Repeat one value or repeat a sequence
Feed the same value repeatedly with itertools.repeat
itertools.repeat(value, count) makes an iterator that yields the same object a specified number of times. For example, this supplies the exponent 2 to pow for each number in range(5):
from itertools import repeat
powers = map(pow, range(5), repeat(2))
print(list(powers)) # [0, 1, 4, 9, 16]
When times is omitted, repeat(value) is unbounded. Pair it with a finite input or specify a count; do not try to consume an unbounded iterator without a stopping mechanism. The itertools reference describes its behavior and starmap.
Replay every element with itertools.cycle
Use itertools.cycle(iterable) to repeat all items in an iterable in the same order indefinitely:
Quick wins for a faster PC:
Clear out junk files and repair common Windows errorsFree Scan →Scan for outdated or missing drivers - takes under a minuteDriver Scan →from itertools import cycle
for color in cycle(["red", "green", "blue"]):
print(color)
# Add a stopping condition or break when appropriate.
Unlike repeat, which yields one object over and over, cycle replays the input’s elements. It saves a copy of those elements, so cycling a very large or unbounded input can use substantial memory. See the Python Functional Programming HOWTO.
Build a repeated sequence with multiplication
For a new list or string containing repeated values, use sequence multiplication:
labels = ["draft"] * 3
cheer = "ha" * 3
print(labels) # ['draft', 'draft', 'draft']
print(cheer) # hahaha
This creates a repeated sequence; it does not execute a block of code. Strings are immutable, so repeating one is safe. With mutable objects, list multiplication repeats references to the same object rather than making independent copies:
shared = [[]] * 3
shared[0].append("x")
print(shared) # [['x'], ['x'], ['x']]
separate = [[] for _ in range(3)]
separate[0].append("x")
print(separate) # [['x'], [], []]
Use a comprehension when each list element needs its own mutable object. The Python 3.14.8 built-in types documentation describes sequence repetition and the distinct behavior of range.
Recommended Free Tools
Best Value
Do not confuse repeated loops with itertools.product
itertools.product(values, repeat=n) does not replay a sequence. It treats the input as repeated dimensions in a Cartesian product, producing combinations. For example, product(["A", "B"], repeat=2) yields ("A", "A"), ("A", "B"), ("B", "A"), and ("B", "B"). Product consumes its input iterables into pools before producing results, so the inputs need to be finite. Consult the itertools documentation when using it for combinations.
Choose the approach that matches the repetition
| Need | Use | How it stops or behaves |
|---|---|---|
| Run statements a known number of times | for _ in range(n): |
Runs once per value yielded by the finite range. |
| Run statements while a condition remains true | while condition: |
Stops when the condition becomes false or the loop exits with break. |
| Call a function with successive inputs | A loop, or map/starmap for suitable iterator workflows |
Follows the input iterable; choose a finite input or another explicit stopping mechanism. |
| Yield one object multiple times | itertools.repeat(value, count) |
Stops at the count; without one, it is unbounded. |
| Replay all items in an iterable | itertools.cycle(iterable) |
Repeats indefinitely and saves a copy of the input items. |
| Create a repeated list or string | sequence * n |
Builds a sequence; mutable list elements may be repeated references. |
Use list(iterator) only when you actually need a list. Keeping a result as an iterator can avoid materializing all its values at once; in contrast, cycle retains a copy of its source items.
Quick Recap
Avoid common repetition mistakes
- Off-by-one counts:
range(5)yields five values, 0 through 4, not 1 through 5. - Unintended infinite loops: a
whilecondition must be able to become false, or the loop needs an intentional exit. - Unbounded iterators:
repeat(x)without a count never ends by itself; give it a count or combine it with a finite operation. - Shared mutable list entries:
[[]] * 3makes three references to one inner list; use a comprehension for separate lists. - Changing a collection during iteration: modifying the collection being traversed can cause surprising behavior. The Python Tutorial recommends iterating over a copy or building a new collection in such cases.
- Multiplying a range:
rangedoes not support sequence multiplication. Use a loop or an appropriate iterator tool for repeated iteration.
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.




