How to repeat something in Python

Learn how to repeat in Python. Discover different methods, tips, real-world applications, and how to debug common errors.

How to repeat something in Python
Published on: 
Fri
Feb 13, 2026
Updated on: 
Tue
Feb 24, 2026
The Replit Team Logo Image
The Replit Team

Repetition is a core concept in programming that automates tasks and processes data efficiently. Python provides powerful tools like for and while loops to handle these operations with simple, readable code.

You'll explore techniques to repeat tasks, from basic loops to advanced methods. You will also get implementation tips, see real-world applications, and learn how to debug common loop-related errors.

Using a simple for loop for repetition

for i in range(5):
print(f"This is repetition {i+1}")--OUTPUT--This is repetition 1
This is repetition 2
This is repetition 3
This is repetition 4
This is repetition 5

The for loop offers a clean way to repeat an action a specific number of times. The key is the range(5) function, which generates a sequence of numbers from 0 to 4. This approach is efficient because it doesn't create an actual list in memory, making it perfect for a fixed number of iterations.

You'll notice the code uses i+1 in the f-string. That’s because range() is zero-indexed, but the output is formatted to show a more human-friendly count that starts from 1.

Basic repetition techniques

Beyond the straightforward for loop, you can control repetition with conditional while loops, customized range() steps, or even the simple * operator.

Using while loops for conditional repetition

count = 0
while count < 5:
print(f"Repeating with while: {count}")
count += 1--OUTPUT--Repeating with while: 0
Repeating with while: 1
Repeating with while: 2
Repeating with while: 3
Repeating with while: 4

A while loop is perfect for when you need to repeat an action until a specific condition is met. Unlike a for loop, it doesn't iterate over a sequence; it just keeps running as long as its condition, in this case count < 5, remains true.

  • The loop checks the condition at the start of each iteration.
  • It's crucial to update the variable inside the loop, like with count += 1. If you don't, the condition will never change, and you'll create an infinite loop.

Customizing range() for flexible repetition

for num in range(2, 11, 2):
print(f"Even number: {num}")--OUTPUT--Even number: 2
Even number: 4
Even number: 6
Even number: 8
Even number: 10

The range() function isn't just for simple counting. You can tailor its output by passing up to three arguments: a start, a stop, and a step value. This lets you create more complex sequences for your loops. In the example, range(2, 11, 2) generates a sequence with specific rules:

  • It starts counting from 2.
  • It stops before reaching 11.
  • It increments by 2 at each step.

This approach is highly efficient for tasks like processing every other item or working with specific numerical patterns, giving you fine-grained control over your iterations.

Repeating sequences with the * operator

repeated_list = [1, 2, 3] * 3
print(repeated_list)

repeated_string = "abc" * 5
print(repeated_string)--OUTPUT--[1, 2, 3, 1, 2, 3, 1, 2, 3]
abcabcabcabcabc

The multiplication operator (*) offers a surprisingly simple way to repeat sequences. It's not just for numbers; you can use it to quickly duplicate the contents of lists and strings.

  • When used with a list like [1, 2, 3] * 3, it creates a new list containing the original elements repeated three times.
  • Similarly, with a string like "abc" * 5, it generates a new string by concatenating "abc" five times.

This method is a concise alternative to using a loop for simple sequence repetition.

Advanced repetition techniques

Moving beyond the fundamental loops, you can leverage more elegant techniques to handle repetition with greater efficiency and more concise code.

Efficient repetition with itertools

import itertools

for item in itertools.repeat("Python", 4):
print(item)

for item in itertools.islice(itertools.cycle([1, 2, 3]), 6):
print(item, end=" ")--OUTPUT--Python
Python
Python
Python
1 2 3 1 2 3

The itertools module provides powerful, memory-efficient tools for handling repetition. These functions generate items one at a time instead of building a full list in memory, which is great for performance.

  • The itertools.repeat("Python", 4) function is straightforward—it produces the same item a specified number of times.
  • For endless repetition, itertools.cycle() loops over a sequence indefinitely. You can pair it with itertools.islice() to grab a finite number of items from the infinite sequence, giving you precise control.

Repeated operations using list comprehensions

repeated = [num for num in range(1, 5) for _ in range(num)]
print(repeated)

modifications = [f"Item-{i}" for i in range(3) for _ in range(2)]
print(modifications)--OUTPUT--[1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
['Item-0', 'Item-0', 'Item-1', 'Item-1', 'Item-2', 'Item-2']

List comprehensions offer a compact syntax for creating lists with repeated items. By nesting for loops within a single line, you can build complex sequences without writing multi-line loops, making your code more declarative and often easier to read.

  • The expression starts with what you want to add to the list, followed by the loops that generate it.
  • In [num for num in range(1, 5) for _ in range(num)], the outer loop provides a number, and the inner loop repeats it that many times.
  • The underscore _ is a common convention for a loop variable you don't intend to use.

Using recursion for controlled repetition

def repeat_action(times, current=0):
if current >= times:
return
print(f"Recursion level: {current}")
repeat_action(times, current + 1)

repeat_action(4)--OUTPUT--Recursion level: 0
Recursion level: 1
Recursion level: 2
Recursion level: 3

Recursion offers an elegant way to handle repetition by having a function call itself. The repeat_action function demonstrates this by repeatedly invoking itself until the current counter meets the specified times limit. This approach breaks a task into smaller, identical sub-tasks.

  • A base case is crucial. Here, if current >= times: return acts as an exit strategy to prevent an infinite loop.
  • The recursive step is the line where the function calls itself, like repeat_action(times, current + 1), moving one step closer to the base case with each call.

While loops are often more straightforward for simple counting, recursion shines when solving problems that naturally break down this way.

Move faster with Replit

Replit is an AI-powered development platform that transforms natural language into working applications. Describe what you want to build, and Replit Agent creates it—complete with databases, APIs, and deployment.

The repetition techniques from this article can be used to build production-ready applications. For example, you could use Replit Agent to:

  • Build a batch processing utility that uses a custom range() step to operate on every Nth item in a dataset.
  • Create a content cycler for a digital kiosk that uses itertools.cycle() to loop through a playlist of media.
  • Deploy a data expansion tool that uses nested list comprehensions to duplicate records for load testing.

Describe your app idea, and Replit Agent will write the code, test it, and deploy the final application for you.

Common errors and challenges

Even with simple loops, you can run into tricky issues like infinite loops, off-by-one errors, and unexpected behavior when modifying lists.

Avoiding infinite loops in while statements

An infinite loop is a common pitfall with while statements. It happens when the loop's condition never becomes false, causing it to run forever. This is usually because you've forgotten to update the variable that the condition checks, so the loop never reaches its exit point.

Fixing off-by-one errors with range()

Off-by-one errors are frequent when using range() because it's easy to forget how it works. The function stops before reaching its specified end number, and it starts from zero by default. For example, range(5) generates numbers from 0 to 4, not 1 to 5, which can cause you to miss the last item in a sequence or try to access an index that doesn't exist.

Safely modifying lists during iteration

Modifying a list while you're iterating over it can lead to unpredictable results. Python's for loop tracks its position by index, so if you remove an item, the loop might skip the next one because the list's size and indices have changed mid-iteration.

  • To avoid this, you should always iterate over a copy of the list, not the original.
  • You can easily create a copy using a slice, like this: for item in my_list[:]:. This lets you safely modify the original my_list inside the loop.

Avoiding infinite loops in while statements

An infinite loop is a classic mistake with while loops. It happens when the loop's condition never becomes false, causing it to run endlessly. This is often because the variable controlling the loop isn't updated. See if you can spot the error.

counter = 0
while counter < 5:
print(f"Current count: {counter}")

The value of counter is never changed inside the loop, so the condition counter < 5 always evaluates to true, creating an endless cycle. The corrected code below shows how to resolve this.

counter = 0
while counter < 5:
print(f"Current count: {counter}")
counter += 1

The solution is adding counter += 1. This line ensures the counter variable increases with each pass, eventually making the condition counter < 5 false and allowing the loop to terminate. Without this update, the loop's condition never changes, leading to an infinite loop. Always make sure the variable controlling your while loop is updated inside the loop body to prevent this common error.

Fixing off-by-one errors with range()

Off-by-one errors are a classic trip-up when using range(). They happen because the function stops just before the specified end value. This can lead to loops that run one time too few, missing the last item you intended to process. See if you can spot the issue in the code below.

for i in range(1, 5):
print(f"Number: {i}")

The loop created with range(1, 5) only prints numbers up to 4, completely missing the number 5. It's a classic off-by-one error. The corrected code below shows how to ensure the loop includes the final number.

for i in range(1, 6):
print(f"Number: {i}")

The solution is to adjust the stop value. By changing range(1, 5) to range(1, 6), the loop now correctly includes the number 5. Remember, the range() function stops before its second argument, so you'll always need to set it one number higher than your desired endpoint. This is a classic gotcha, especially when you're iterating over sequences with specific start and end points.

Safely modifying lists during iteration

Modifying a list while you're iterating over it can lead to tricky, unexpected behavior. When you remove an item, the list's indices shift, which often causes the loop to skip the very next element. See if you can spot the issue below.

numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num % 2 == 0:
numbers.remove(num)
print(numbers)

When the code removes 2, the list shrinks, causing the loop to skip over the next item, 3. This happens because the list's indices shift mid-iteration. The corrected code below shows a safer way to accomplish this.

numbers = [1, 2, 3, 4, 5]
numbers_to_keep = [num for num in numbers if num % 2 != 0]
print(numbers_to_keep)

The fix works by creating an entirely new list instead of changing the original one mid-loop. A list comprehension—[num for num in numbers if num % 2 != 0]—builds a fresh list with only the desired elements. This approach is safer because it completely avoids the index-shifting issues that cause skipped items. It's the standard, Pythonic way to filter a collection without unexpected side effects. Always be cautious when modifying any sequence you're iterating through.

Real-world applications

Understanding how to fix loop errors prepares you to tackle real-world tasks, from processing text data to simulating web scraping.

Processing text data with for loops

A for loop is perfect for processing text line by line, and you can use enumerate() to automatically track each line number as you go.

sample_text = "Python\nRepetition\nTechniques"
for line_number, line in enumerate(sample_text.splitlines(), 1):
print(f"Line {line_number}: {line}")

This pattern is great for handling text. The splitlines() method breaks the string into a list of lines, and enumerate() adds a counter to each one.

  • The loop iterates over the pairs created by enumerate().
  • Setting the start value to 1 in enumerate(..., 1) makes the counter behave like a line number, starting from one instead of zero.
  • Each pair is unpacked into the line_number and line variables, which are then used for formatted printing.

Simulating web scraping with repetition

Repetition is also key for tasks like web scraping, where you can use a for loop to methodically work through a list of pages and collect information from each.

pages = [f"page{i}.html" for i in range(1, 5)]
scraped_data = []

for page in pages:
print(f"Scraping {page}...")
# Simulate extracting data from each page
data = f"Content from {page}"
scraped_data.append(data)

print(f"Collected {len(scraped_data)} items:")
for item in scraped_data:
print(item)

This example showcases a common data collection pattern. It begins by using a list comprehension to dynamically create a list of filenames to process. An empty list, scraped_data, is also set up to store the results from each step.

  • The for loop iterates through each generated filename.
  • Inside the loop, a placeholder string simulates fetching data from the file.
  • The append() method adds this new data to the scraped_data list, building up the final collection.

After the loop finishes, the code prints the contents of scraped_data to confirm that all items were collected successfully.

Get started with Replit

Turn these techniques into a real tool. Tell Replit Agent: “Build a batch file renamer using a for loop” or “Create a password generator that uses itertools to create random character sequences.”

Replit Agent writes the code, tests for errors, and deploys your application from a single prompt. Start building with Replit.

Get started free

Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.

Get started for free

Create & deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.