Codectionary / Developer documentation / Python

for

The for loop in Python is used to iterate over sequences like lists, tuples, strings, or any iterable object. Unlike traditional for loops in other languages that use counters, Python's for loop is more like a "for each" loop, automatically handling the iteration details. It's one of the most commonly used constructs in Python for processing collections and repeating actions.

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

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!")

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}")

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}")

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!")

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

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()

# Practical example
passwords = ["abc", "password123", "12345", "secure_pass"]

for pwd in passwords:
    if len(pwd) < 8:
        print(f"{pwd} - Too short, skipping...")
        continue
    print(f"{pwd} - Valid password")
    if pwd == "secure_pass":
        print("Found secure password!")
        break

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

At a glance

Purpose
Scripting and general-purpose applications
File extension
.py
Runs in
Python interpreter
Usually used with
Python standard library and packages

Specifications & further reading

Related Python documentation