Python:Python For Loops and the range() Function
Python•Loops

Python For Loops and the range() Function

Unlike C-style counter loops, Python for loops are iterator-based. They step through items in an iterable directly, with range() generating numeric sequences.

Syntax

for item in iterable: # execute code with item

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
itemLoop VariableTakes the value of the current sequence element.
iterableIterable ObjectList, range, string, dictionary, or generator.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing Python locally:

# 1. Iterating with range(start, stop, step)
print("--- Squares Table ---")
for num in range(1, 5):
    print(f"{num} squared = {num ** 2}")

# 2. Iterating with enumerate() for index & value
print("\n--- Tech Stack Ranking ---")
languages = ["Python", "JavaScript", "Rust"]
for index, lang in enumerate(languages, start=1):
    print(f"#{index}: {lang}")
Expected Output:
--- Squares Table ---
1 squared = 1
2 squared = 4
3 squared = 9
4 squared = 16

--- Tech Stack Ranking ---
#1: Python
#2: JavaScript
#3: Rust

How It Works: Step-by-Step

  • Lines 3-4: range(1, 5) produces numbers 1, 2, 3, 4 (stop 5 is exclusive).
  • Lines 9-10: enumerate() pairs index with the corresponding element automatically.

Key Concepts

  • range(start, stop, step) is zero-indexed by default and lazy-evaluated.
  • enumerate(seq, start=1) produces tuples of (index, item) during iteration.
  • Python for loops do not require manual index incrementing.

Common Mistake: Expecting range(1, 10) to include 10

The stop parameter in range() is exclusive. Use range(1, 11) to include 10.

❌ Incorrect
for i in range(1, 5): # Runs only up to 4
    pass
✅ Correct
for i in range(1, 6): # Runs from 1 through 5 inclusive
    pass

Related Python Tutorials & Compiler

Run and test Python on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Python Online Compiler