Python Basics — For Loop

2 minute read

For Loop

Python’s for loop iterates over any sequence — lists, strings, tuples, dictionaries, ranges, and more. It’s the most common loop type in Python.

Basic Syntax

for item in sequence:
    # do something with item
colors = ["red", "green", "blue"]

for color in colors:
    print(color)

Output:

red
green
blue

Iterating Over Different Types

Lists

numbers = [10, 20, 30, 40]
total = 0

for num in numbers:
    total += num

print(f"Sum: {total}")  # Sum: 100

Strings

word = "Python"

for char in word:
    print(char, end=" ")

Output:

P y t h o n

Tuples

coordinates = [(1, 2), (3, 4), (5, 6)]

for x, y in coordinates:
    print(f"x={x}, y={y}")

Output:

x=1, y=2
x=3, y=4
x=5, y=6

Dictionaries

scores = {"Alice": 95, "Bob": 87, "Charlie": 92}

# Iterate over keys (default)
for name in scores:
    print(name)

# Iterate over key-value pairs
for name, score in scores.items():
    print(f"{name}: {score}")

# Iterate over values only
for score in scores.values():
    print(score)

range() Function

range() generates a sequence of numbers — perfect for counted loops.

# range(stop) — 0 to stop-1
for i in range(5):
    print(i, end=" ")  # 0 1 2 3 4
# range(start, stop)
for i in range(1, 6):
    print(i, end=" ")  # 1 2 3 4 5
# range(start, stop, step)
for i in range(0, 10, 2):
    print(i, end=" ")  # 0 2 4 6 8
# Counting down
for i in range(5, 0, -1):
    print(i, end=" ")  # 5 4 3 2 1

enumerate() — Track Index

When you need both the index and the value:

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

for index, fruit in enumerate(fruits):
    print(f"{index}: {fruit}")

Output:

0: apple
1: banana
2: cherry
# Start counting from 1
for index, fruit in enumerate(fruits, start=1):
    print(f"{index}. {fruit}")

Output:

1. apple
2. banana
3. cherry

zip() — Parallel Iteration

Iterate over multiple sequences simultaneously:

names = ["Alice", "Bob", "Charlie"]
scores = [95, 87, 92]

for name, score in zip(names, scores):
    print(f"{name}: {score}")

Output:

Alice: 95
Bob: 87
Charlie: 92

zip() stops at the shortest sequence.

for-else

The else block runs only when the loop completes without a break:

numbers = [2, 4, 6, 8]

for num in numbers:
    if num % 2 != 0:
        print(f"Found odd number: {num}")
        break
else:
    print("All numbers are even!")

Output:

All numbers are even!
numbers = [2, 4, 5, 8]

for num in numbers:
    if num % 2 != 0:
        print(f"Found odd number: {num}")
        break
else:
    print("All numbers are even!")

Output:

Found odd number: 5

Common Patterns

Building a List

squares = []
for i in range(1, 6):
    squares.append(i ** 2)
print(squares)  # [1, 4, 9, 16, 25]

Filtering

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = []

for num in numbers:
    if num % 2 == 0:
        evens.append(num)

print(evens)  # [2, 4, 6, 8, 10]

Running Total

expenses = [50.00, 25.50, 100.00, 35.75]
total = 0

for expense in expenses:
    total += expense
    print(f"  + ${expense:.2f} → Running total: ${total:.2f}")

print(f"\nTotal: ${total:.2f}")

Output:

  + $50.00 → Running total: $50.00
  + $25.50 → Running total: $75.50
  + $100.00 → Running total: $175.50
  + $35.75 → Running total: $211.25

Total: $211.25

Summary

  • for item in sequence: iterates over any iterable
  • Works with lists, strings, tuples, dictionaries, ranges
  • range(start, stop, step) generates number sequences
  • enumerate() gives both index and value
  • zip() pairs up multiple iterables
  • for-else runs the else block when no break occurs

Next up: While Loop →

Updated: