For Loops

Difficulty: Beginner

The `for` loop in Python iterates over any iterable object -- lists, strings, tuples, dictionaries, ranges, and more. Unlike C-style for loops, Python's for loop directly gives you each element rather than an index.

The `range()` function generates a sequence of numbers and is commonly used when you need to loop a specific number of times or need index-based iteration. It accepts up to three arguments: `range(start, stop, step)`, where `stop` is exclusive.

When you need both the index and the value while iterating, use `enumerate()` instead of manually tracking a counter variable. It returns pairs of (index, value) and accepts an optional `start` parameter to change the starting index.

You can also unpack tuples directly in the for loop header, which is especially useful when iterating over lists of tuples or dictionary items.

Code examples

Iterating over different sequences

# List
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

# String
for char in "Hi!":
    print(char, end=" ")
print()

A for loop pulls one element at a time from the iterable. Strings are iterable character by character. The end=' ' parameter in print prevents the newline.

range() with start, stop, step

# Count from 1 to 5
for i in range(1, 6):
    print(i, end=" ")
print()

# Even numbers from 0 to 8
for i in range(0, 10, 2):
    print(i, end=" ")
print()

# Countdown
for i in range(5, 0, -1):
    print(i, end=" ")
print()

range(start, stop, step) generates numbers from start (inclusive) to stop (exclusive). A negative step counts downward.

enumerate() for index + value

languages = ["Python", "JavaScript", "Rust"]

for index, lang in enumerate(languages):
    print(f"{index}: {lang}")

print("---")

# Starting index at 1
for rank, lang in enumerate(languages, start=1):
    print(f"#{rank} {lang}")

enumerate() wraps an iterable and yields (index, element) tuples. The start parameter offsets the index counter.

Key points

Concepts covered

for loop, range(), iterating sequences, enumerate(), loop unpacking