Last modified: Mar 28, 2026 By Alexander Williams
Python For i in Range Loop Tutorial
One of the first and most powerful concepts you will learn in Python is the loop. The for loop, combined with the range() function, is a cornerstone of programming. It allows you to repeat actions efficiently.
This article will explain the for i in range pattern in detail. You will learn its syntax, how it works, and see many practical examples. By the end, you will be able to use it confidently in your own code.
What is the Range Function?
Before diving into the loop, you must understand range(). It is a built-in Python function that generates a sequence of numbers. It does not create a list in memory. Instead, it produces numbers one by one, which is memory efficient.
For a deep dive into its parameters and behavior, check out our Python Range Function Guide: Syntax & Examples.
The range() function can be used in three ways:
- range(stop): Starts at 0, goes up to (but not including) the stop value.
- range(start, stop): Starts at 'start', goes up to 'stop'.
- range(start, stop, step): Uses a 'step' value to increment or decrement.
Basic Syntax of For i in Range
The basic structure is simple. You use the for keyword, a variable name (like i), the in keyword, and then a call to range().
# Basic loop that runs 5 times (0 to 4)
for i in range(5):
print(f"Iteration number: {i}")
Iteration number: 0
Iteration number: 1
Iteration number: 2
Iteration number: 3
Iteration number: 4
In this example, i takes on each value from the sequence generated by range(5). The loop body, which is indented, executes once for each value.
Using Start, Stop, and Step Parameters
You have full control over the sequence. Let's look at examples using all parameters.
# Loop from 2 to 8 (exclusive)
print("Loop from 2 to 8:")
for num in range(2, 9):
print(num, end=' ')
print() # New line
# Loop from 10 down to 0, stepping by -2
print("\nLoop from 10 to 0, step -2:")
for countdown in range(10, -1, -2):
print(countdown, end=' ')
Loop from 2 to 8:
2 3 4 5 6 7 8
Loop from 10 to 0, step -2:
10 8 6 4 2 0
The step parameter is powerful. It allows you to skip numbers or count backwards. A negative step means you are creating a descending sequence.
Practical Examples and Common Use Cases
Knowing syntax is good. Applying it is better. Here are common tasks solved with for i in range.
1. Iterating Over a List by Index
Sometimes you need the index of an item, not just the item itself. Use range(len(list)).
fruits = ['apple', 'banana', 'cherry', 'date']
for i in range(len(fruits)):
print(f"Index {i} contains: {fruits[i]}")
Index 0 contains: apple
Index 1 contains: banana
Index 2 contains: cherry
Index 3 contains: date
2. Creating Repeated Actions
Need to do something a fixed number of times? This is perfect for range().
# Print a message 3 times
for _ in range(3):
print("Loading...")
# Note: Using '_' is a convention for an unused loop variable.
Loading...
Loading...
Loading...
3. Building Sequences and Calculations
You can use the loop to build new data or perform cumulative calculations.
# Calculate the sum of numbers from 1 to 100
total = 0
for number in range(1, 101):
total += number
print(f"The sum of 1 to 100 is: {total}")
# Create a list of even numbers
evens = []
for n in range(0, 21, 2):
evens.append(n)
print(f"Even numbers list: {evens}")
The sum of 1 to 100 is: 5050
Even numbers list: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
Important Tips and Best Practices
Use these tips to write cleaner and more efficient loops.
- Choose Descriptive Variable Names: Use
indexorrowinstead of justiwhen it makes the code clearer. - Prefer Direct Iteration: If you don't need the index, loop directly over the list:
for fruit in fruits:. It's more Pythonic. - Remember Range is Exclusive:
range(5)gives you 0,1,2,3,4. The stop value is never included. This is a common source of off-by-one errors. - Combine with enumerate: For getting both index and value,
enumerate()is often better thanrange(len()).
Common Mistakes to Avoid
Beginners often run into a few specific issues. Be aware of these pitfalls.
Modifying the List You're Iterating Over: Changing a list's length while looping over its indices can cause unexpected behavior or errors. It's usually safer to create a new list.
Confusing the Number of Iterations: Remember that range(10) causes 10 iterations (0-9), not 9. Always double-check your start and stop values.
Forgetting the Colon: The colon (:) at the end of the for line is required. Missing it is a syntax error.
Conclusion
The for i in range loop is a fundamental and versatile tool in Python. It provides precise control over iteration counts and sequences. You learned its basic syntax, how to use its start, stop, and step parameters, and saw practical examples from indexing lists to performing calculations.
Mastering this loop pattern will form a solid foundation for more advanced programming concepts. Remember to use it when you need a specific number of repetitions or control over an index. For other cases, like simply going through items in a collection, more direct iteration methods are preferable. Keep practicing with different parameters and examples to build your intuition.
To further solidify your understanding of the core function behind this loop, exploring our dedicated Python Range Function Guide is highly recommended.