October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk4 min

How to Repeat Code, Functions and Values in Python

Use loops to repeat Python code or function calls, itertools to repeat iterator values, and sequence multiplication to build repeated strings and lists.

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.

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:

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

Call a function repeatedly

Put a function call inside a loop. If the function should receive different arguments each time, iterate over those inputs:

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

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

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

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.

Avoid common repetition mistakes

  • Off-by-one counts: range(5) yields five values, 0 through 4, not 1 through 5.
  • Unintended infinite loops: a while condition 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: [[]] * 3 makes 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: range does 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.

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

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.