Python For Loop: Sequence Traversal, range(), enumerate() & zip()

In Python, the for loop is an iterator-based loop that steps through items of any iterable sequence (such as a list, string, tuple, dictionary, or generator) one by one. It eliminates index tracking variables and array bounds errors, making code exceptionally clean and expressive.


1. Iterating Over Sequences

# Iterating over a string:
for char in "PYTHON":
    print(char, end=" ")
# Output: P Y T H O N 

# Iterating over a list:
languages = ["Python", "Rust", "Go", "TypeScript"]
for lang in languages:
    print(f"Modern language: {lang}")

2. The range(start, stop, step) Function

The range() function produces an immutable sequence of integers on demand without loading all numbers into memory at once:

# 1. Single argument: range(stop) -> 0 to stop-1
for i in range(5):
    print(i, end=" ")  # 0 1 2 3 4

# 2. Two arguments: range(start, stop)
for i in range(10, 15):
    print(i, end=" ")  # 10 11 12 13 14

# 3. Three arguments: range(start, stop, step)
for i in range(10, 30, 5):
    print(i, end=" ")  # 10 15 20 25

# 4. Counting backwards with negative step:
for i in range(5, 0, -1):
    print(i, end=" ")  # 5 4 3 2 1

3. Essential For Loop Helpers: enumerate() and zip()

A. enumerate(iterable, start): Loop with Index & Value

toppers = ["Priya", "Rahul", "Ananya"]

for rank, name in enumerate(toppers, start=1):
    print(f"Rank #{rank}: {name}")
# Rank #1: Priya
# Rank #2: Rahul
# Rank #3: Ananya

B. zip(*iterables): Loop Over Multiple Lists in Parallel

students = ["Aman", "Rhea", "Vikram"]
marks = [92, 88, 95]

for name, score in zip(students, marks):
    print(f"{name} scored {score}/100")

4. The for...else Block

Like the while loop, an else block attached to a for loop executes only if the loop completes all iterations without encountering a break:

# Prime Number Checker using for-else:
num = 29

for i in range(2, int(num ** 0.5) + 1):
    if num % i == 0:
        print(f"{num} is composite (divisible by {i}).")
        break
else:
    print(f"{num} is a PRIME number!")

Frequently Asked Questions (FAQ)

Does range(1, 10) include the number 10?

No. In Python ranges and slices, the stop boundary is strictly exclusive. range(1, 10) yields numbers from 1 up to 9.
Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!