How to iterate over an integer in Python
Learn how to iterate over integers in Python. Discover different methods, tips, real-world applications, and how to debug common errors.

Python integers aren't directly iterable, which can be a hurdle. To loop from zero to a number, you can use the range() function to generate a sequence first.
You'll explore this and other techniques for integer iteration. You will also find practical tips, real-world applications, and common debugging advice to help you confidently handle this skill.
Using range() to iterate through integers
for i in range(5):
print(i, end=" ")--OUTPUT--0 1 2 3 4
The range() function is what makes this loop possible. It generates a sequence of numbers on demand, which is more memory efficient than creating an actual list. When you use range(5), you're creating an object that represents the sequence from 0 up to, but not including, 5.
The for loop then pulls each number from this sequence, which is why the output is 0 1 2 3 4. Key behaviors of range() with a single argument include:
- It starts counting from 0 by default.
- It stops before reaching the specified number.
Basic iteration techniques
The range() function is more flexible than it first appears, allowing you to specify start and end points, custom step sizes, and even count backward.
Specifying start and end values with range()
for i in range(3, 8):
print(i, end=" ")--OUTPUT--3 4 5 6 7
When you give range() two arguments, you're setting a specific start and end for your sequence. The first number is where the count begins, and it's included in the output. The second number is where the count stops, and it's always excluded.
- In
range(3, 8), the sequence starts at3. - The loop continues until it reaches
8, but8itself is not part of the sequence.
This gives you precise control over the segment of numbers you want to work with.
Using a custom step with range()
for i in range(2, 12, 3):
print(i, end=" ")--OUTPUT--2 5 8 11
Adding a third argument to range() lets you define a custom step size. This number determines the increment between each value in the sequence. It's a powerful way to skip numbers instead of just counting one by one.
- In
range(2, 12, 3), the sequence starts at2. - It then adds the step value,
3, to generate the next numbers:5,8, and11. - The loop stops before reaching the end value of
12.
Iterating over integers in reverse
for i in range(10, 0, -2):
print(i, end=" ")--OUTPUT--10 8 6 4 2
You can iterate in reverse by providing a negative step value. For range() to count down, the start value must be greater than the end value. In the example range(10, 0, -2), the sequence is generated as follows:
- It begins at
10. - The step value
-2causes it to count down by twos. - The loop stops before reaching the end value of
0, producing the sequence10, 8, 6, 4, 2.
Advanced integer iteration
Beyond the standard range() function, Python offers more advanced ways to work with integers, from iterating through digits to using list comprehensions and generators.
Iterating through digits of an integer
number = 12345
for digit in str(number):
print(int(digit), end=" ")--OUTPUT--1 2 3 4 5
You can't loop through an integer's digits directly, but there's a simple trick: convert it to a string. The str(number) function transforms the integer into a sequence of characters that you can iterate over.
- A
forloop can then process each character individually. - Inside the loop, you'll need to use
int(digit)to convert the character back into a number before you can use it in any calculations.
Using list comprehensions with integers
squares = [i**2 for i in range(1, 6)]
print(squares)--OUTPUT--[1, 4, 9, 16, 25]
List comprehensions provide a concise syntax for creating lists. It’s like a one-line for loop that builds a list for you. The expression [i**2 for i in range(1, 6)] is a perfect example of this in action.
- The
for i in range(1, 6)part iterates through the numbers 1 to 5. - For each number, the expression
i**2is evaluated to calculate its square. - The results are collected into the new list, giving you
[1, 4, 9, 16, 25].
This is often more readable than a traditional loop with an append() method.
Using generators for memory-efficient iteration
even_numbers = (i for i in range(10) if i % 2 == 0)
print(list(even_numbers))--OUTPUT--[0, 2, 4, 6, 8]
A generator expression is syntactically similar to a list comprehension but uses parentheses. Instead of building a full list in memory, it creates a generator object. This object produces values one at a time as you loop over it, making it highly memory-efficient—especially for large sequences.
- The expression
(i for i in range(10) if i % 2 == 0)doesn't store the full list of numbers. - It yields each value on demand when iterated over.
- Using
list()on the generator forces it to produce all its values at once for display.
Move faster with Replit
Replit is an AI-powered development platform that transforms natural language into working applications. You can describe what you want to build, and Replit Agent creates it—complete with databases, APIs, and deployment.
For the integer iteration techniques covered in this article, Replit Agent can turn them into production-ready tools. You could use it to:
- Build a test data generator that creates specific numerical sequences using custom start, stop, and step values from
range(). - Create a validation utility that checks ID numbers by iterating through their digits to calculate a checksum.
- Deploy a data analysis tool that efficiently processes large numerical datasets using memory-saving generators.
Describe your application, and Replit Agent handles the rest—writing the code, running tests, and fixing issues automatically. Turn your ideas into working software with Replit Agent.
Common errors and challenges
Even with a function as useful as range(), you can run into a few common pitfalls, especially with loop boundaries and step values.
An off-by-one error is a classic programming mistake, and it often happens with range() because the function excludes the stop value. If you want to process numbers from 1 to 10, for example, writing range(1, 10) will only give you numbers up to 9. You're left one short.
To fix this, you just need to remember to set your stop value to one more than the final number you want. For a sequence that includes the number 10, you'd use range(1, 11).
Another common issue appears when you use range() with the len() function to iterate over a sequence by index. The correct pattern is range(len(my_list)), which generates indices from 0 to the final index. A mistake is to add 1, like range(len(my_list) + 1), which will cause an IndexError because you'll try to access an element that doesn't exist.
When you need to count down, you have to get two things right: the step value must be negative, and the start value must be greater than the end value. It's easy to forget one of these. For instance, range(10, 0) won't work because Python's default step is 1, and it can't get from 10 to 0 by counting up. The correct call is range(10, 0, -1), which properly counts down from 10 to 1.
Fixing off-by-one errors with range()
The off-by-one error is a classic bug that often stems from how range() handles its stop value. It's easy to forget that the loop won't include the final number. See what happens when you try to print numbers 1 to 10 using range(1, 10).
# Trying to print numbers from 1 to 10
for i in range(1, 10):
print(i, end=" ")
The output is 1 2 3 4 5 6 7 8 9. Because the loop stops at the number before the second argument in range(), it never reaches 10. The corrected code below shows how to adjust for this.
# Correctly printing numbers from 1 to 10
for i in range(1, 11):
print(i, end=" ")
The corrected code uses range(1, 11) to successfully print numbers up to and including 10. By increasing the stop value by one, you compensate for range()'s behavior of excluding the endpoint. You'll need to make this adjustment anytime your loop requires an inclusive upper boundary, such as when iterating through a specific set of numbers or processing data up to a final count.
Debugging incorrect loop bounds when using range() with len()
It's also common to accidentally shorten your loop when using range() with len(). You might subtract one, like range(len(data) - 1), to be safe, but this causes the loop to skip the final element. The following code demonstrates this issue.
data = [10, 20, 30, 40]
for i in range(len(data) - 1):
print(data[i], end=" ")
Here, range(len(data) - 1) creates a sequence from 0 to 2, because len(data) is 4. Your loop stops one item short, missing the last element. The following example shows the simple adjustment needed to include every item.
data = [10, 20, 30, 40]
for i in range(len(data)):
print(data[i], end=" ")
The correct approach uses range(len(data)). Since list indices start at 0, len(data) provides the perfect stop value for range(), which generates indices from 0 up to the final valid index. This ensures your loop accesses every element. It’s a common pattern you'll need when your loop requires access to an item's position, such as when you're modifying a list in place or comparing adjacent elements.
Using the correct step value with range() for decreasing sequences
Forgetting the negative step value when creating a decreasing sequence is a common pitfall. The range() function defaults to a step of +1, so if your start value is greater than the end, the loop won't execute. The code below shows this in action.
# Attempting to count down from 10 to 1
for i in range(10, 1):
print(i, end=" ")
The loop produces no output because range() tries to count up from 10 to 1 by default. This generates an empty sequence, so the loop body never executes. The corrected code below demonstrates the proper fix.
# Counting down from 10 to 1
for i in range(10, 0, -1):
print(i, end=" ")
The corrected code works by providing a negative step value, which tells the range() function to count backward. To get a sequence from 10 down to 1, you must use range(10, 0, -1). The loop starts at 10 and stops just before it reaches 0, making 1 the final number. You'll need to remember this anytime you want to iterate through a sequence in reverse, such as when processing items from last to first.
Real-world applications
Beyond debugging loops, you can use integer iteration with range() for practical tasks like creating multiplication tables or calculating Fibonacci numbers.
Generating a multiplication table with range()
A for loop paired with the range() function is a classic way to generate the multipliers for a multiplication table.
number = 7
print(f"Multiplication table for {number}:")
for i in range(1, 11):
print(f"{number} × {i} = {number * i}")
This snippet builds a multiplication table for the number 7. The for loop drives the process, using range(1, 11) to generate a sequence of multipliers from 1 to 10.
- Inside the loop, the variable
iholds the current multiplier for each step. - An f-string then formats the output, embedding the
number, the currenti, and the calculated productnumber * iinto a readable line.
This approach efficiently prints the full table without you needing to write each line manually.
Calculating Fibonacci numbers with range()
You can also use range() to generate the indices needed to build a Fibonacci sequence, where each new number is the sum of the two before it.
fib = [0, 1]
for i in range(2, 10):
fib.append(fib[i-1] + fib[i-2])
print(f"First 10 Fibonacci numbers: {fib}")
This code generates the sequence by first creating a list, fib, seeded with 0 and 1. The loop then runs for indices 2 through 9, which is handled by range(2, 10).
- Inside the loop, the code calculates the next number in the sequence.
- It does this by adding the two most recent values in the list, which are found using the indices
i-1andi-2. - The result is then added to the end of the list with
fib.append().
This process repeats until the list holds the first ten numbers.
Get started with Replit
Put your new skills to use by building a tool. Tell Replit Agent to “build a prime number generator for a given range” or “create a tool that calculates factorials using a loop.”
The agent writes the code, runs tests, and handles deployment for you. It turns your description into a finished product. Start building with Replit.
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.
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.

.png)
.png)
.png)