Python for Loop with range(): Examples You Can Run

Python for Loop with range(): Examples You Can Run


If you’re learning Python, the for loop with range is one of the first tools you’ll use to repeat actions a fixed number of times. In this beginner-friendly guide, you’ll learn how to use range in a Python for loop, understand the syntax, practice with simple programs, and avoid common mistakes. We’ll also cover best practices like using enumerate and reversed for clear, safe code. For more basics and related lessons, explore the full Python section at CodDesire Python Tutorials.

What is range and why use it in a for loop?

Python for loop with range examples: visual of stop, start-stop, and step iteration flows
Stop, start–stop, and step in range(), shown as iteration paths.

In Python, a for loop iterates over items in any iterable (lists, strings, files, etc.). The built-in range type creates a memory‑efficient, immutable sequence of integers that’s perfect for counted loops—when you want to loop a specific number of times or over a sequence of numbers.

  • range(stop): numbers from 0 up to, but not including, stop.
  • range(start, stop): numbers from start up to, but not including, stop.
  • range(start, stop, step): numbers from start to stop (exclusive), jumping by step. Negative steps count down.

Important points:

  • stop is exclusive: the sequence ends just before stop.
  • range stores only start/stop/step and computes values on demand (not a list or generator).
  • Arguments must be integers (or objects implementing __index__); step cannot be 0.

Key takeaways: Python for loop with range examples
  • range(start, stop, step) uses an exclusive stop (it stops just before stop).
  • To include an endpoint b, use range(a, b + 1). For countdowns, use a negative step.
  • range is memory‑light (it doesn’t build a full list); it only accepts integers and step ≠ 0.
  • Prefer enumerate(seq) for index+value, and reversed(range(n)) for clear countdowns.
  • Test edge cases: empty ranges like range(5, 5) iterate zero times.

Python for loop syntax for beginners

Python for loop with range examples: reverse counting and nested loop grid traversal
Reverse steps and nested loops with range(), visualized by arrows and grids.

Basic for loop with a counted range:

for i in range(n):
# your code here
pass

With start, stop, and step:

for i in range(start, stop, step):
# your code here
pass

Python for loop with range examples

1) Loop through numbers 0 to 4

This is the simplest pattern—range(5) yields 0, 1, 2, 3, 4.

for i in range(5):
print(i)
Output
0
1
2
3
4

2) Print numbers 1 to 10 using a Python for loop

Use a start value of 1 and stop at 11 (because stop is exclusive).

for i in range(1, 11):
print(i)
Output
1
2
3
4
5
6
7
8
9
10

3) Python for loop with range and step value

Skip numbers by setting step. Here are even numbers from 2 to 10.

for i in range(2, 11, 2):
print(i)
Output
2
4
6
8
10

4) Countdown with a negative step

Count down by using a negative step. This loop prints 5 to 0 inclusive.

for i in range(5, -1, -1):
print(i)
Output
5
4
3
2
1
0

5) Custom step sizes

Jump by 3 each time, stopping before 0.

for i in range(10, 0, -3):
print(i)
Output
10
7
4
1

How to use range in a Python for loop: start, stop, and step explained

Let’s break down the long‑tail topic: python for loop with range start stop step examples.

  • Start: where counting begins (default 0).
  • Stop: where counting ends (exclusive).
  • Step: how much to add each time (default 1, can be negative).

Examples you can try:

# 0 to 9 (default start=0, step=1)
for i in range(10):
print(i, end=" ")
print()

# 3 to 7 (stops before 8)
for i in range(3, 8):
print(i, end=" ")
print()

# 1, 4, 7 (step = 3)
for i in range(1, 10, 3):
print(i, end=" ")
print()

# -2, -4, -6 (negative numbers)
for i in range(-2, -7, -2):
print(i, end=" ")
Output
0 1 2 3 4 5 6 7 8 9 
3 4 5 6 7 
1 4 7 
-2 -4 -6

Choose the right range() pattern for your goal
Goal
Repeat an action N times

Use

for _ in range(n):

Goal
Inclusive range a..b

Use

for i in range(a, b + 1):

Goal
Countdown from s to t

Use

for i in range(s, t - 1, -1):

Tip: for i in reversed(range(n)) is clear for n−1..0

Goal
Step by k (skip numbers)

Use

for i in range(a, b, k):

Goal
Need index + value

Use

for i, x in enumerate(seq, start=1):

Only use range(len(seq)) for in‑place updates

Why does range(1, 5) stop at 4?

This is a common beginner question: Why does range(1, 5) stop at 4 in Python? The stop value is exclusive. This design makes it easy to express common patterns, such as looping exactly n times with range(n), slicing sequences, and aligning with zero-based indexing. If you need to include 5, write range(1, 6).

Looping over items vs. looping over indexes

Often you do not need indexes at all—iterate directly over the items. When you need both index and value, use enumerate for readability and safety. Only use range(len(...)) when explicit indexing is required (e.g., writing back to the same list or accessing parallel structures by index).

Best practice: enumerate for index and value

students = ["Ava", "Ben", "Chen"]
for idx, name in enumerate(students, start=1):
print(idx, name)
Output
1 Ava
2 Ben
3 Chen

Iterate over list indices using range and len in Python

Use this when you must access or modify by position.

scores = [50, 65, 80]
for i in range(len(scores)):
scores[i] += 5 # curve each score
print(scores)
Output
[55, 70, 85]

Parallel iteration without indexes

Use zip to loop over two lists together.

names = ["Ava", "Ben", "Chen"]
marks = [85, 90, 92]
for name, mark in zip(names, marks):
print(f"{name}: {mark}")
Output
Ava: 85
Ben: 90
Chen: 92

Reverse iteration

Use reversed(range(n)) or a negative step. Both are fine; reversed(range(n)) can be clearer when counting down from n-1 to 0.

for i in reversed(range(6)): # 5 down to 0
print(i, end=" ")
Output
5 4 3 2 1 0

Qualitative guide: choose a loop pattern (longer bar = better)
Beginner clarity
Direct items: for x in seq

enumerate(seq)

reversed(range(n))

range(start, stop, -1)

range(len(seq))

Lower bug risk
Direct items: for x in seq

enumerate(seq)

reversed(range(n))

range(start, stop, -1)

range(len(seq))

This chart is qualitative guidance for beginners working through python for loop with range examples.

Small comparison: choosing the right loop tool

Goal Recommended pattern Example
Count N times range(n) for _ in range(10): ...
Index + value enumerate(seq[, start]) for i, x in enumerate(a, 1): ...
Reverse order reversed(seq) or reversed(range(n)) for i in reversed(range(5)):
Parallel sequences zip(a, b) for x, y in zip(a, b): ...
Need exact indices range(len(seq)) for i in range(len(a)):

Real task: search with for–else

Python’s for loop supports an else clause that runs only if the loop did not hit a break. It’s handy for searches. Example: a simple prime test.

x = 29
for n in range(2, x):
if x % n == 0:
print(f"{x} is divisible by {n}, so it is not prime.")
break
else:
print(f"{x} is prime.")
Output
29 is prime.

Common off-by-one mistakes with Python range (and fixes)

  • Expecting the stop value to be included
    Mistake:

    for i in range(1, 5): # prints 1..4, not 1..5
    # fix: use range(1, 6)
  • Writing a zero step
    range(1, 10, 0) raises ValueError: step argument must not be zero. Pick a positive or negative non-zero step.
  • Using floats with range
    range requires integers. For decimal steps, use a counter and compute values inside the loop:

    for i in range(5): # 0..4
    x = 0.5 * i # 0.0, 0.5, 1.0, 1.5, 2.0
    print(x)
  • Building a list unnecessarily
    list(range(1_000_000)) creates a huge list in memory. If you only need to loop or sum, use range directly:

    total = sum(range(1_000_000))
  • Indexing when not needed
    Prefer direct iteration or enumerate over range(len(seq)) unless you truly need indices.

Mini practice: try these yourself

  1. Print the squares of numbers from 1 to 5.
  2. Print every third number from 3 to 24 (inclusive).
  3. Countdown from 10 to 1, then print “Go!”.
  4. Given data = [2, -3, 7, -1], add 10 to each negative number using index-based updates.
  5. Use enumerate to print line numbers for a list of strings.

FAQ: Python for loop range explained

What does range do in a Python for loop?

range produces an efficient, read-only sequence of integers that a for loop can iterate over without creating a full list in memory. It supports start, stop, and step (including negative steps).

How do I write a for loop from 1 to 10 in Python?

for i in range(1, 11):
print(i)

How can I change the step value in Python range?

Use the third argument: range(start, stop, step).

for i in range(0, 20, 5): # 0,5,10,15
print(i)

Why does range(1, 5) stop at 4 in Python?

The stop value is exclusive by design, so range(1, 5) yields 1, 2, 3, 4. To include 5, write range(1, 6).

How do I loop through indexes with range and len in Python?

items = ["a", "b", "c"]
for i in range(len(items)):
print(i, items[i])

Tips and best practices

  • Use for _ in range(n) when the loop variable isn’t needed.
  • Prefer enumerate for index+value loops; use start=1 for human-friendly numbering.
  • Use reversed(range(n)) for clear countdowns.
  • Avoid converting range to a list unless you truly need list behavior.
  • Test edge cases: empty ranges (e.g., range(5, 5)) produce no iterations.

More range function in Python examples

Quick patterns you’ll use often:

# Repeat an action 3 times
for _ in range(3):
print("Hello")

# Sum of first 100 natural numbers
total = sum(range(1, 101))
print(total)

# Index-aware updates with conditions
nums = [1, -2, 3, -4, 5]
for i in range(len(nums)):
if nums[i] < 0:
nums[i] = 0
print(nums)
Output
Hello
Hello
Hello
5050
[1, 0, 3, 0, 5]

Where this fits in your learning path

Mastering counted loops with range is a foundation for solving repetitive tasks, generating sequences, building simple simulations, and practicing algorithmic thinking. After this, try combining for loops with lists, strings, and dictionaries, and learn patterns like enumerate, zip, and comprehensions. Continue with more beginner topics in our Python for Beginners hub.

Sources / Further reading

Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted