Skip to content
PythonControl Flowbeginner18 min read

for Loops and range()

Learn how for loops repeat code, how range() generates integer sequences, and how to trace each iteration.

In this lesson, you will learn

  • ✓Explain how a for loop processes items one at a time.
  • ✓Use range() with one, two, and three arguments.
  • ✓Explain why the stop value of range() is excluded.
  • ✓Trace loop variables and predict exact program output.
  • ✓Use for loops to calculate totals and solve simple counting problems.
  • ✓Recognize common loop mistakes, including incorrect indentation and range() boundaries.

1. What Is a for Loop?

A loop is a programming construct that repeats instructions. A for loop executes its body once for each item obtained from an iterable. An iterable is an object that can provide its items one at a time, such as a list, a string, or a range.

The loop variable receives the current item on each iteration. Python then executes the indented loop body. When the body finishes, Python moves to the next item. When there are no items left, the loop ends and execution continues with the first statement after the loop.

The general syntax is:

for variable in iterable:

# Statements to repeat

The colon ends the loop header, and indentation identifies the loop body. In Python, the indented statements belong to the loop. A loop variable is not a special keyword; it is a normal variable name chosen by the programmer.

Repeat an operation for each item

Repeat an operation for each item
python
for fruit in ["apple", "banana", "mango"]:
print(fruit)
Output
apple banana mango

Python gets the first item, "apple", assigns it to fruit, and executes print(fruit). On the next iteration, fruit refers to "banana". On the third iteration, it refers to "mango". After all three items have been processed, the loop ends. print() displays each item on a separate line because each call ends with a newline by default.

2. Using range() with One Argument

The built-in range() function represents a sequence of integers. It is commonly used with for loops when you need to repeat an operation a certain number of times.

When range() receives one argument, range(stop), it starts at 0 and generates integers up to, but not including, stop. Therefore, range(4) represents the integers 0, 1, 2, and 3.

The stop value is excluded. This is an important rule: range(4) contains four integers, not five. If stop is zero or negative, range(stop) produces no integers because the default step is positive and the starting value is 0.

Print numbers from 0 to 3

Print numbers from 0 to 3
python
for number in range(4):
print(number)
Output
0 1 2 3

range(4) represents 0, 1, 2, and 3. The loop body executes four times, with number receiving one integer per iteration. The integer 4 is not included because range() excludes its stop value.

Note

If you want a loop to execute n times for a non-negative integer n, range(n) is a common choice. The loop variable starts at 0, but you do not have to use that variable inside the loop body.

3. Using range() with Start and Stop

You can pass two arguments to range(): range(start, stop). The sequence begins at start and proceeds toward stop using the default step of 1. The stop value is still excluded.

For example, range(2, 6) represents 2, 3, 4, and 5. It does not include 6.

The number of integers in range(start, stop), when start is less than or equal to stop and the default step is 1, is stop - start. If start is equal to stop, or start is greater than stop, the range is empty.

Print numbers from 2 to 5

Print numbers from 2 to 5
python
for number in range(2, 6):
print(number)
Output
2 3 4 5

The first argument, 2, is the starting value. The second argument, 6, is the excluded stopping value. Python assigns 2, 3, 4, and 5 to number in successive iterations. The loop ends before number can receive 6.

4. Using range() with a Step

The three-argument form is range(start, stop, step). The step determines how much the sequence changes between consecutive integers.

With a positive step, the sequence moves upward. With a negative step, it moves downward. The step cannot be zero; range() raises ValueError if you supply a step of 0.

For a positive step, the sequence stops before reaching or passing the stop boundary. For a negative step, it stops before reaching or passing the lower stop boundary. Choose the direction of the step to match the direction from start toward stop.

Print even numbers from 2 to 10

Print even numbers from 2 to 10
python
for number in range(2, 11, 2):
print(number)
Output
2 4 6 8 10

The starting value is 2, the stop value is 11, and the step is 2. Each iteration increases number by 2. The sequence is 2, 4, 6, 8, and 10. The stop value 11 is excluded, but 10 is included because it is reached before the boundary.

Note

Remember the argument order: start, stop, step. The step controls the direction and distance between values; it does not change the rule that the stop value is excluded.

5. Trace a for Loop Step by Step

A dry run means manually tracing a program to understand what happens at each step. For a for loop, record the current loop variable, any important variable changes, and any output produced during each iteration.

Consider a loop that adds the integers from 1 through 3. The total variable stores the running sum. The statement total += number is equivalent to total = total + number.

The loop body executes once for each value produced by range(1, 4). The final print(total) is outside the loop, so it executes only after all iterations have finished.

Calculate a running total

Calculate a running total
python
total = 0
 
for number in range(1, 4):
total += number
print("number:", number, "total:", total)
 
print("Final total:", total)
Output
number: 1 total: 1 number: 2 total: 3 number: 3 total: 6 Final total: 6

Before the loop starts, total is 0. During the first iteration, number is 1 and total becomes 0 + 1 = 1. During the second iteration, number is 2 and total becomes 1 + 2 = 3. During the third iteration, number is 3 and total becomes 3 + 3 = 6. After the loop, the final print() displays the completed total of 6. In print(), multiple arguments are separated by a space by default. That is why the labels and values appear with spaces in the output.

Note

When tracing a loop, do not jump directly to the final answer. Write down the loop variable and updated values after every iteration. This makes off-by-one errors and incorrect calculations easier to find.

6. Practical Applications and Edge Cases

For loops are useful for counting, processing collections, calculating totals, and repeating a fixed number of operations. Choose the loop based on the items you need to process, rather than using range() automatically for every task.

An empty range causes the loop body to execute zero times. This can happen when start equals stop or when the step moves in the wrong direction. An empty range is valid and does not cause an error by itself.

The stop boundary is a frequent source of mistakes. If you need to include the integer 5 while counting upward by one from 1, use range(1, 6), not range(1, 5).

A for loop does not require the loop variable to be named i. Use a meaningful name such as number, score, or fruit when it makes the code easier to understand. Use i or j when a short index-style name is appropriate.

The built-in range() returns a range object, not a list. It represents the integer sequence without creating a list containing every value. You can convert it to a list with list(range(...)) when you specifically need a list.

Handle an empty range

Handle an empty range
python
for number in range(3, 3):
print(number)
 
print("Loop finished")
Output
Loop finished

range(3, 3) is empty because its start and stop values are equal. The loop body never executes, so no number is printed. Python continues with the statement after the loop and prints Loop finished.

Caution

Do not use a step of zero: range(1, 5, 0) raises ValueError. Also remember that a loop with an empty range is not necessarily a bug; it simply has no iterations. Decide whether that behavior is correct for the requirement.

Common pitfalls to avoid

Real debugging lessons and exact syntax contrasts to avoid runtime bugs

#1 Expecting range(5) to produce 1, 2, 3, 4, 5.

Why it happens: range(stop) starts at 0 and excludes stop, so range(5) yields 0 through 4.

Incorrect Approach
script.py
python
Expecting range(5) to produce 1, 2, 3, 4, 5.
Correct Solution
script.py
python
range(5) produces 0, 1, 2, 3, 4. The one-argument form starts at 0 and excludes the stop value. Use range(1, 6) to produce 1 through 5.

Key takeaway: range(5) produces 0, 1, 2, 3, 4. The one-argument form starts at 0 and excludes the stop value. Use range(1, 6) to produce 1 through 5.

#2 Forgetting the colon at the end of the for statement.

Why it happens: A for statement requires a colon before its indented loop body.

Incorrect Approach
script.py
python
Forgetting the colon at the end of the for statement.
Correct Solution
script.py
python
Write a colon after the loop header, as in for number in range(3):.

Key takeaway: Write a colon after the loop header, as in for number in range(3):.

#3 Incorrectly indenting the loop body.

Why it happens: The loop body must be indented to show which statements repeat on each iteration.

Incorrect Approach
script.py
python
Incorrectly indenting the loop body.
Correct Solution
script.py
python
Indent the statements that must repeat under the for statement. Statements outside that indentation run after the loop.

Key takeaway: Indent the statements that must repeat under the for statement. Statements outside that indentation run after the loop.

#4 Using a positive step when counting downward.

Why it happens: A negative step is needed for a descending range; a positive step moves upward and may produce no values when start is greater than or equal to stop.

Incorrect Approach
script.py
python
Using a positive step when counting downward.
Correct Solution
script.py
python
Use a negative step, such as range(5, 0, -1), to count from 5 down to 1.

Key takeaway: Use a negative step, such as range(5, 0, -1), to count from 5 down to 1.

#5 Using zero as the step.

Why it happens: A step of zero cannot advance a range and Python raises ValueError.

Incorrect Approach
script.py
python
Using zero as the step.
Correct Solution
script.py
python
Use a nonzero step. A zero step causes range() to raise ValueError.

Key takeaway: Use a nonzero step. A zero step causes range() to raise ValueError.

#6 Thinking the loop variable automatically resets to its original value inside every iteration.

Why it happens: The loop variable is assigned the next item on each iteration, so its value changes as the loop progresses.

Incorrect Approach
script.py
python
Thinking the loop variable automatically resets to its original value inside every iteration.
Correct Solution
script.py
python
The loop variable is assigned the next item on each iteration. If you change it inside the body, Python will assign the next item when the next iteration begins.

Key takeaway: The loop variable is assigned the next item on each iteration. If you change it inside the body, Python will assign the next item when the next iteration begins.

#7 Putting a final calculation or summary print inside the loop when it should run only once.

Why it happens: Statements placed inside the loop execute on every iteration; put final totals or summary output after the loop when they should happen once.

Incorrect Approach
script.py
python
Putting a final calculation or summary print inside the loop when it should run only once.
Correct Solution
script.py
python
Check the indentation. Place statements after the loop at the outer indentation level if they should execute once after all iterations.

Key takeaway: Check the indentation. Place statements after the loop at the outer indentation level if they should execute once after all iterations.

#8 Assuming range() creates a list.

Why it happens: range() represents an integer sequence efficiently and is not itself a list; use list(range(...)) when a list is explicitly needed.

Incorrect Approach
script.py
python
Assuming range() creates a list.
Correct Solution
script.py
python
range() returns a range object representing an integer sequence. Use list(range(...)) if a list is required.

Key takeaway: range() returns a range object representing an integer sequence. Use list(range(...)) if a list is required.

Ready for hands-on challenges?

Test your skills with shuffled coding challenges in the Practice Arena.

Practice Arena →

Technical and placement interview questions

Frequently tested interview questions with detailed, full answers (click to expand)

Q1:What is a for loop in Python?
Answer:
A for loop iterates over the items provided by an iterable and executes its body once for each item. Common iterables include lists, strings, and range objects.
Q2:What is range() used for?
Answer:
range() represents a sequence of integers, commonly used for counting and controlling the number of loop iterations. It supports range(stop), range(start, stop), and range(start, stop, step).
Q3:Why does range() exclude the stop value?
Answer:
The excluded stop boundary makes it straightforward to express sequence lengths and counts. For example, range(5) contains exactly five integers: 0 through 4. To include 5 while counting upward from 1, use range(1, 6).
Q4:What is the difference between range(5) and range(1, 5)?
Answer:
range(5) represents 0, 1, 2, 3, and 4. range(1, 5) represents 1, 2, 3, and 4. Both exclude their stop value, but their starting values differ.
Q5:How do you count backward with range()?
Answer:
Use a negative step. For example, range(5, 0, -1) represents 5, 4, 3, 2, and 1. The stop value 0 is excluded.
Q6:What happens if the range is empty?
Answer:
The for loop body executes zero times, and Python continues with the statement after the loop. An empty range can occur when the start and stop are equal or when the step points in the wrong direction.
Q7:What is the difference between range() and list(range())?
Answer:
range() returns a range object that represents an integer sequence. list(range(...)) creates a list containing the integers in that sequence.

Key takeaways

  • A for loop executes its body once for each item provided by an iterable.
  • range(stop) starts at 0 and excludes stop.
  • range(start, stop) lets you choose the starting value while still excluding stop.
  • range(start, stop, step) controls the starting value, stopping boundary, and direction or increment.
  • A positive step counts upward; a negative step counts downward; a zero step raises ValueError.
  • The loop body must be indented correctly, and statements outside the loop run after iteration finishes.
  • A dry run helps track the loop variable, running totals, and exact output.
  • Test boundary cases, including empty ranges, and verify the expected output.
Was this lesson helpful?
Found an error? Report an issue

Related Topics & Next Steps

4 Recommended Lessons

Strengthen your Python foundation with these complementary core lessons: