How to repeat something in Python
Learn how to repeat in Python using loops and other methods. Discover tips, real-world examples, and how to debug common repetition errors.

To repeat actions in Python is a fundamental skill for automation and data processing. Python provides powerful constructs like for and while loops to execute code multiple times efficiently.
In this article, you'll learn various repetition techniques and practical tips. We'll cover real-world applications and common debugging advice to help you master loops and write more effective Python code.
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 is a concise way to repeat an action a specific number of times. The key to this operation is the range(5) function, which generates a sequence of numbers from 0 up to, but not including, 5. The loop then runs the indented code once for each number in that sequence.
You'll notice the f-string uses i+1. This is a common practice to display a more intuitive, 1-based count in the output (1 to 5) instead of the 0-based index (0 to 4) that range() provides by default.
Basic repetition techniques
Building on the for loop, you can also control repetition based on conditions using while or create custom sequences with range() and the * 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 offers a different way to repeat actions. Instead of running a set number of times, it continues as long as a specific condition remains true. In this example, the loop executes as long as the count variable is less than 5.
- The loop checks the condition
count < 5before each iteration. - It's crucial to include a line like
count += 1. This update ensures the condition eventually becomes false, preventing 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 limited to just a stop value; you can also specify a start and a step. This lets you create more complex sequences for your loops. In this example, range(2, 11, 2) generates a sequence with specific rules.
- The sequence starts at
2. - It stops just before it reaches
11. - The step value of
2means it only includes every second number.
This approach is perfect for when you need to iterate over a specific slice of numbers, like only the even ones in a given range.
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
In Python, the * operator isn't just for multiplication. You can also use it to repeat sequences like lists and strings, which is a clean way to build new data from a pattern. The operator takes a sequence and an integer that defines how many times to repeat it.
- For a list,
[1, 2, 3] * 3creates a new list where the original sequence is repeated three times. - With a string,
"abc" * 5produces a new string by joining "abc" to itself five times.
Advanced repetition techniques
With the fundamentals down, you can now write more efficient and elegant repetition code using advanced tools like the itertools module, list comprehensions, and recursion.
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
Python's itertools module offers powerful, memory-efficient tools for creating complex iterators. It's perfect for when you need to handle repetitions that are either very large or infinite without consuming all your system's memory.
- The
itertools.repeat("Python", 4)function is straightforward. It generates the given object a specified number of times. - For endless repetition,
itertools.cycle([1, 2, 3])creates an iterator that repeats the sequence indefinitely. You can then pair it withitertools.islice()to take a finite slice from the beginning, preventing an infinite loop.
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 provide a compact syntax for creating lists from other sequences. By nesting a second for loop, you can perform repeated actions within a single, readable line. It’s a powerful way to build a new list where elements from an outer loop are duplicated or transformed by an inner loop.
- In the first example,
[num for num in range(1, 5) for _ in range(num)], the inner loop runsnumtimes, effectively repeating each number by its own value. - The second example repeats each generated string twice, showing how to create duplicates for each item in a sequence.
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 is a powerful concept where a function calls itself to repeat an action. In this example, the repeat_action function continues to call itself until a specific "base case" is satisfied, which prevents it from running indefinitely. It’s a different way of thinking about repetition compared to a standard loop.
- The condition
if current >= times:is the base case. It’s the essential stop signal for the recursion. - With each call, the function executes its task and then invokes itself again with an updated counter,
current + 1, moving one step closer to meeting the base case.
Move faster with Replit
Replit is an AI-powered development platform where you can start coding Python instantly. It comes with all Python dependencies pre-installed, so you can skip the setup and focus on building. Instead of just practicing individual techniques, you can use Agent 4 to build complete applications directly from a description.
You can move from learning loops to shipping a full product. Just describe what you want to build, and Agent 4 can create tools like these:
- A batch-renaming utility that uses a
forloop to apply a sequential naming convention to hundreds of files. - A test data generator that uses the
*operator to create a large list of repeated items for load testing an API. - A round-robin scheduler that assigns tasks by cycling through a list of team members, powered by
itertools.
Simply describe your app, and Replit will write the code, test it, and fix issues automatically, all within your browser.
Common errors and challenges
When working with loops, you'll likely encounter a few common pitfalls, but they're easy to fix once you know what to look for.
Avoiding infinite loops in while statements
Infinite loops are a classic problem with while statements, occurring when the loop's condition never becomes false. This typically happens if you forget to update the variable being checked—for example, by omitting a counter like count += 1. To prevent this, always ensure your loop includes logic that will eventually cause it to terminate.
Fixing off-by-one errors with range()
Off-by-one errors are also frequent, especially with the range() function. They happen because it's easy to forget that the stop value is exclusive; range(5) produces numbers from 0 to 4, not 1 to 5. This small detail can cause your loop to run one time too many or too few, or even trigger an IndexError when accessing list items.
To avoid this, always be mindful of your start and stop values. If you need to iterate through a list of five items, range(len(my_list)) is perfect because list indices are also 0-based, running from 0 to 4.
Safely modifying lists during iteration
Modifying a list while you're iterating over it can lead to unpredictable results. When you remove an item, the list's size changes, and the indices of the remaining elements shift, which often causes your loop to skip items.
- A safer approach is to iterate over a copy of the list. You can create a shallow copy using slice notation:
for item in my_list[:]:. - This lets you safely modify the original
my_listbecause your loop is working from a separate, static version.
Another common strategy is to build an entirely new list with only the elements you want to keep, rather than removing items from the original one.
Avoiding infinite loops in while statements
A while loop becomes infinite when its condition never evaluates to false, causing the program to hang. This classic error often happens when the loop variable isn't updated inside the loop's body. The following code demonstrates this exact problem.
counter = 0
while counter < 5:
print(f"Current count: {counter}")
Because the counter variable is never updated within the loop, the condition counter < 5 will always be true. This traps the program in an endless cycle. The corrected code below shows how to resolve it.
counter = 0
while counter < 5:
print(f"Current count: {counter}")
counter += 1
The solution is the addition of counter += 1. This line is crucial because it increments the counter with each pass, ensuring the condition counter < 5 eventually becomes false and the loop terminates. Without this update, the condition never changes, causing the program to hang. Always ensure your while loops contain logic that progresses toward their termination condition, especially when the logic depends on a changing variable.
Fixing off-by-one errors with range()
Off-by-one errors are a common trip-up when using the range() function. They happen when your loop runs one time too many or too few, often because the stop value is exclusive. The code below shows a classic example of this mistake.
for i in range(1, 5):
print(f"Number: {i}")
This code prints numbers 1 through 4. The loop stops before reaching 5 because the range() function excludes the final number. The corrected code below shows how to adjust the range to get the intended output.
for i in range(1, 6):
print(f"Number: {i}")
The fix is simple: changing the stop value to 6 in range(1, 6) ensures the loop includes the number 5 in its output. Since range() is exclusive of its stop value, this adjustment makes the sequence run up to the desired endpoint. This detail is crucial when you're iterating through a specific number of items or need to process a complete numerical series. Always double-check your range boundaries to prevent these subtle errors.
Safely modifying lists during iteration
It's a classic pitfall: changing a list while you're looping through it. This can lead to strange results, like your loop skipping over items it should have processed. The code below shows what happens when you try to remove elements mid-iteration.
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num % 2 == 0:
numbers.remove(num)
print(numbers)
When numbers.remove(num) is called for the number 2, the list shrinks. The loop's internal counter advances to the next index, which now points to 4, causing it to skip over 3 entirely. See the fix below.
numbers = [1, 2, 3, 4, 5]
numbers_to_keep = [num for num in numbers if num % 2 != 0]
print(numbers_to_keep)
The fix avoids modifying the list in place. Instead, a list comprehension—[num for num in numbers if num % 2 != 0]—builds an entirely new list with only the desired elements. This is a much safer and more predictable approach because the original list remains untouched during the iteration. You're not pulling the rug out from under the loop as it runs, which prevents skipped items and other unexpected behavior when filtering data.
Real-world applications
Beyond the syntax and common pitfalls, these repetition techniques are the engine behind practical tasks like processing text files and scraping data from websites.
Processing text data with for loops
One of the most common uses for a for loop is to process text data, such as reading a file or a multi-line string one line at a time.
sample_text = "Python\nRepetition\nTechniques"
for line_number, line in enumerate(sample_text.splitlines(), 1):
print(f"Line {line_number}: {line}")
This code efficiently processes multi-line text by combining two powerful Python features. The splitlines() method first converts the string into a list, with each line as a separate item. Then, the enumerate() function iterates over that list, providing both the content and a counter.
- The loop unpacks each pair into
line_numberandline. - Setting the start value to
1inenumerate()makes the count 1-based, which is perfect for user-facing line numbers.
This approach is cleaner than manually managing a counter variable inside the loop. When building text processing applications, vibe coding can help you prototype these data workflows quickly.
Simulating web scraping with repetition
You can use a for loop to automate web scraping tasks, such as iterating through a list of URLs to collect data from each one.
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 demonstrates a common pattern for data collection. It starts by using a list comprehension to generate a list of target pages, which simulates a list of URLs you'd want to scrape. A second list, scraped_data, is initialized to store the information you'll gather.
The core of the operation is the for loop:
- It iterates through each
pagein the target list. - For each page, it simulates fetching content and adds it to the
scraped_datalist using theappend()method.
This approach systematically processes each source and collects the results in one place. For more complex data collection tasks, AI coding with Python can help automate the entire scraping workflow.
Get started with Replit
Now, turn your knowledge into a real tool. Give Replit Agent a prompt like: “A script that generates a CSV file with 1,000 rows of sample user data” or “A task scheduler that uses itertools.cycle.”
Replit Agent will write the code, test for errors, and help you deploy your application directly from your browser. Start building with Replit.
Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.
Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.



