Codectionary / Developer documentation / Python

for

A for loop takes successive items from an iterable and assigns each item to its loop target before running the body. Lists, strings, dictionaries, ranges and generators are iterable. The number of items does not need to be known beforehand.

How it works

Iterate directly over values when possible. Use enumerate() when you also need a counter, and dictionary.items() when you need each key and value. A dictionary preserves insertion order in Python 3.7 and later; a set does not promise a useful display order.

The body runs once per item and zero times for an empty iterable. When an iterator is exhausted, the loop finishes. A generator is consumed as it is iterated, so a second loop over the same exhausted generator produces no items.

In nested loops, the inner loop runs for each outer item. Three outer iterations with three inner iterations produce nine pairs. Consider how work grows before nesting loops over large collections.

Common mistakes and boundaries

Changing a collection’s structure while iterating it can skip values or raise an error. Build a new collection or iterate an appropriate copy when adding or removing items.

The loop target remains bound after a nonempty loop; if the loop never ran, it may never have been assigned. Do not depend on a final loop value without handling the empty case.

Try it yourself

Use enumerate to print a numbered shopping list. Test an empty list, then a one-item list. Next filter out blank entries into a new list rather than removing items during iteration.

Syntax

for variable in iterable:
    # code to execute for each item

Examples

List Iteration

Iterating through lists to process each element.

fruits = ["apple", "banana", "orange", "grape"]

for fruit in fruits:
    print(f"I like {fruit}")

numbers = [1, 2, 3, 4, 5]
total = 0

for num in numbers:
    total += num

print(f"Sum: {total}")  # 15
  1. The first loop prints each fruit; the second accumulates a total. sum(numbers) is the concise built-in alternative for this simple summation.
  2. Expected output: I like apple I like banana I like orange I like grape Sum: 15

Range Function

Using range() to iterate a specific number of times or generate number sequences.

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

# Count from 1 to 5
for i in range(1, 6):
    print(i)  # 1, 2, 3, 4, 5

# Count by steps
for i in range(0, 10, 2):
    print(i)  # 0, 2, 4, 6, 8

# Countdown
for i in range(5, 0, -1):
    print(f"{i}...")  # 5... 4... 3... 2... 1...
print("Liftoff!")
  1. Every range excludes its stop boundary. The negative step moves the countdown towards zero.
  2. Expected output: 0 1 2 3 4 1 2 3 4 5 0 2 4 6 8 5... 4... 3... 2... 1... Liftoff!

String Iteration

Iterating through characters in a string.

message = "Python"

for char in message:
    print(char)  # P, y, t, h, o, n

# Count vowels
text = "Hello World"
vowels = "aeiouAEIOU"
vowel_count = 0

for char in text:
    if char in vowels:
        vowel_count += 1

print(f"Vowels found: {vowel_count}")
  1. String iteration visits Unicode code points. This simple English vowel counter does not handle every language or every user-perceived character.
  2. Expected output: P y t h o n Vowels found: 3

Enumerate Function

Getting both index and value while iterating using enumerate().

fruits = ["apple", "banana", "orange"]

for index, fruit in enumerate(fruits):
    print(f"{index + 1}. {fruit}")
# Output:
# 1. apple
# 2. banana
# 3. orange

# Start counting from different number
for index, fruit in enumerate(fruits, start=10):
    print(f"Item {index}: {fruit}")
  1. enumerate yields a counter and a value. Its start changes the counter without changing the underlying sequence.
  2. Expected output: 1. apple 2. banana 3. orange Item 10: apple Item 11: banana Item 12: orange

Dictionary Iteration

Iterating through dictionary keys, values, or both.

student_scores = {
    "Alice": 85,
    "Bob": 92,
    "Charlie": 78
}

# Iterate over keys
for name in student_scores:
    print(f"{name}: {student_scores[name]}")

# Iterate over values
for score in student_scores.values():
    print(f"Score: {score}")

# Iterate over key-value pairs
for name, score in student_scores.items():
    print(f"{name} scored {score}")
    if score >= 90:
        print("  Excellent!")
  1. Direct dictionary iteration yields keys; values() yields scores; items() yields pairs that are unpacked into two names.
  2. Expected output: Alice: 85 Bob: 92 Charlie: 78 Score: 85 Score: 92 Score: 78 Alice scored 85 Bob scored 92 Excellent! Charlie scored 78

Nested Loops

Using loops within loops for multi-dimensional iteration.

# Multiplication table
for i in range(1, 4):
    for j in range(1, 4):
        product = i * j
        print(f"{i} × {j} = {product}")
    print()  # Empty line between tables

# Pattern printing
for row in range(1, 5):
    for col in range(row):
        print("*", end=" ")
    print()  # New line after each row
  1. Each outer value gets a complete inner pass. The final nested loops print a growing number of stars, with one newline per row.
  2. Expected output: 1 × 1 = 1 1 × 2 = 2 1 × 3 = 3 2 × 1 = 2 2 × 2 = 4 2 × 3 = 6 3 × 1 = 3 3 × 2 = 6 3 × 3 = 9 * * * * * * * * * *

Break and Continue

Controlling loop execution with break and continue statements.

# Break - exit loop early
for num in range(1, 11):
    if num == 5:
        print("Found 5! Stopping...")
        break
    print(num)

print()

# Continue - skip to next iteration
for num in range(1, 6):
    if num == 3:
        continue  # Skip 3
    print(num)  # Prints 1, 2, 4, 5

print()

# Filter and stop using ordinary task labels
for task in ["", "draft", "review", "publish"]:
    if not task:
        continue
    if task == "review":
        print("Found review")
        break
    print(f"Checked: {task}")
  1. The first loop stops at five; the second skips three. The final example filters blank task labels and stops at a target without printing sensitive data.
  2. Expected output: 1 2 3 4 Found 5! Stopping... 1 2 4 5 Checked: draft Found review

Best practices

  • Use descriptive variable names in for loops (for student in students: instead of for s in students:)
  • Use enumerate() when you need both index and value
  • Prefer list comprehensions for simple transformations ([x*2 for x in numbers])
  • Avoid modifying the list you're iterating over - create a new list instead
  • Use range(len(list)) only when absolutely necessary - prefer direct iteration
  • Break complex nested loops into separate functions for better readability

Runtime & versions

Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Python language reference

Specifications & further reading