Understand for i in range Loop in Python

As a Python developer with experience, I’ve used for i in range() loops countless times in my projects. This simple yet powerful construct is one of Python’s most fundamental tools for iteration.

In this article, I’ll walk you through everything you need to know about the for i in range() loop in Python. From basic usage to advanced techniques, you’ll learn how to leverage this loop for various programming tasks.

Whether you’re a beginner or an experienced developer looking to refresh your knowledge, this guide will help you master this essential Python construct.

What is the for i in range() Loop?

The for i in range() loop is a Python construct that allows you to iterate over a sequence of numbers. It’s particularly useful when you need to execute a block of code a specific number of times.

The range() function generates a sequence of numbers that the loop can iterate through. It’s one of the most commonly used functions in Python loops.

At its core, this loop combines two Python elements:

  1. The for loop statement
  2. The range() function

Basic Syntax of for i in range()

Here’s the basic syntax of a for i in range() loop:

for i in range(stop):
    # Code to execute in each iteration

Let me break down what happens here:

  1. i is the loop variable that takes each value from the range
  2. range(stop) generates numbers from 0 up to (but not including) stop
  3. The indented code block is executed for each value of i

For example:

for i in range(5):
    print(i)

This will output:

0
1
2
3
4

Different Ways to Use range()

The range() function is quite flexible. Here are the three ways you can use it:

Method 1: range(stop)

This is the simplest form, where you specify only the stop value:

for i in range(5):
    print(i)  # Prints 0, 1, 2, 3, 4

Method 2: range(start, stop)

You can specify both start and stop values:

for i in range(2, 8):
    print(i)  # Prints 2, 3, 4, 5, 6, 7

I executed the above example code and added the screenshot below.

for i in range Loop in Python

Method 3: range(start, stop, step)

You can also specify a step value, which determines the increment between numbers:

for i in range(1, 10, 2):
    print(i)  # Prints 1, 3, 5, 7, 9

Practical Examples of for i in range() in Python

Let’s look at some real-world examples where for i in range() can be useful:

Example 1: Process a List of US States

This example iterates through a list of U.S. states and prints each state with its corresponding number.

us_states = ["California", "Texas", "Florida", "New York", "Pennsylvania"]

for i in range(len(us_states)):
    print(f"State #{i+1}: {us_states[i]}")

Output:

State #1: California
State #2: Texas
State #3: Florida
State #4: New York
State #5: Pennsylvania

I executed the above example code and added the screenshot below.

Understand for i in range Loop in Python

Example 2: Calculate Compound Interest

This example calculates and displays the compound interest growth over 10 years.

principal = 10000  # $10,000 initial investment
rate = 0.05  # 5% annual interest rate
years = 10

print("Year\tBalance")
print("-----------------")
for i in range(years + 1):
    balance = principal * (1 + rate) ** i
    print(f"{i}\t${balance:.2f}")

Output:

Year    Balance
-----------------
0       $10000.00
1       $10500.00
2       $11025.00
3       $11576.25
...and so on

Example 3: Countdown Timer

This example demonstrates a simple countdown timer using Python’s `time.sleep()` function.

import time

print("Launching in:")
for i in range(10, 0, -1):
    print(i)
    time.sleep(1)
print("Liftoff!")

Advanced Techniques with for i in range() in Python

Let me show you some advanced techniques with for i in range() in Python.

Nested Loops

You can nest for i in range() loops for multi-dimensional iteration:

# Creating a simple multiplication table
for i in range(1, 6):
    for j in range(1, 6):
        print(f"{i} × {j} = {i*j}", end="\t")
    print()  # New line after each row

I executed the above example code and added the screenshot below.

Understand for i in range Loop Python

Use enumerate() as an Alternative

While for i in range(len(list)) works, Python offers a more elegant solution with enumerate():

us_states = ["California", "Texas", "Florida", "New York", "Pennsylvania"]

# Instead of:
# for i in range(len(us_states)):
#     print(f"State #{i+1}: {us_states[i]}")

# Use:
for i, state in enumerate(us_states, 1):
    print(f"State #{i}: {state}")

Combine with List Comprehensions

range() works beautifully with list comprehensions:

# Generate a list of squares from 1 to 10
squares = [i**2 for i in range(1, 11)]
print(squares)  # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Common Mistakes and How to Avoid Them

Let me show you some common mistakes and how to avoid them.

Mistake 1: Off-by-One Errors

Remember that range(n) generates numbers from 0 to n-1, not n:

# Incorrect if you want numbers 1 to 5
for i in range(5):
    print(i)  # Prints 0, 1, 2, 3, 4

# Correct if you want numbers 1 to 5
for i in range(1, 6):
    print(i)  # Prints 1, 2, 3, 4, 5

Mistake 2: Modify the Loop Variable

Avoid modifying the loop variable within the loop:

# This won't work as expected
for i in range(5):
    print(i)
    i = i + 2  # This has no effect on the next iteration

Mistake 3: Inefficient Range Use

For large ranges, use range() directly instead of converting to a list:

# Inefficient for large ranges (in Python 2)
for i in list(range(1000000)):
    pass

# Efficient (works in both Python 2 and 3)
for i in range(1000000):
    pass

When to Use Python’s for i in range() vs. Other Loops

Let’s understand when to use Python’s for i in range() and other loops.

Use Python’s for i in range() when:

  1. You need to execute code a specific number of times
  2. You need the index values during iteration
  3. You want to iterate through a sequence with a specific step size

Consider alternatives when:

  1. You simply want to iterate through items in a collection (use for item in collection)
  2. You need to loop until a condition is met (use a while loop)
  3. You need to iterate through dictionary keys and values (use items())

Performance Considerations

In Python 3, range() returns a range object, which is a sequence type that generates numbers on demand rather than storing the entire sequence in memory. This makes it memory-efficient for large ranges.

For example, this won’t consume gigabytes of memory:

for i in range(1000000000):
    if i > 10:  # Just process the first few elements
        break
    print(i)

I executed the above example code and added the screenshot below.

Python for i in range Loop

I hope you found this guide helpful for understanding the for i in range() loop in Python. This fundamental construct is something you’ll use almost daily as a Python developer, and mastering it will significantly improve your coding efficiency.

Remember that while for i in range() is powerful, Python also offers many other iteration tools. Choose the one that makes your code most readable and efficient for the task at hand.

Other Python articles you may also like:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.