Python For Loop
Tutorial 16 of 65 · pythondeck.com Python course
The for loop iterates over any iterable: lists, tuples, strings, dicts, files, generators. range produces arithmetic progressions efficiently. enumerate adds an index, zip pairs iterables, reversed reverses them.
For loops iterate over elements produced by an iterable—sequences, files, generators—not just numeric ranges. They are the default way to process collections in idiomatic Python.
Understanding iterables vs iterators explains why you can loop once over a generator and why modifying a list while iterating requires care.
for item in iterable: binds each value; no manual index unless needed.
range(n), range(start, stop, step) for arithmetic progressions.
enumerate(iterable, start=0) yields index and value together.
zip(a, b) pairs parallel iterables; stops at shortest.
Loop else executes if no break occurred.
Comprehensions are compact for loops that build lists, sets, or dicts.
Iterate dicts with .items() when you need keys and values. Unpacking in the loop head: for k, v in d.items().
Do not mutate a list while iterating it—iterate a copy or build a new list comprehension.
Generators and files are single-pass—list() if you need two passes; unpack with for a, b in pairs.
Modifying list size during for x in lst without copying.
Using range(len(lst)) when for x in lst or enumerate suffices.
Exhausting a generator twice and getting no items the second time.
Shadowing the loop variable after the loop and reusing it by mistake.
Prefer direct iteration over indices; use enumerate when index is required.
Use zip with strict=True (3.10+) when parallel sequences must match length.
Push heavy inner logic into functions to keep loop bodies short.
Choose comprehensions for simple maps/filters; loops when side effects dominate.
Name the loop variable after the element (for row in rows), not opaque i unless numeric.
Re-read the examples below with these ideas in mind; change variable names and inputs to match your own project.
The program below demonstrates range. Read the comments on each line, run the code, then change names or values to see how the output shifts.
# Example: range
# Run in the REPL or save as a .py file and execute with python.
for i in range(0, 10, 2):
print(i)
This sample walks through enumerate / zip in a small, runnable script. Paste it into the REPL or save it as a .py file before you continue to the next block.
# Example: enumerate / zip
# Run in the REPL or save as a .py file and execute with python.
names = ["Ada", "Linus", "Grace"]
years = [1815, 1969, 1906]
for i, (n, y) in enumerate(zip(names, years), start=1):
print(i, n, y)
Here is a hands-on illustration of nested. Follow the inline comments first; only then execute the snippet and compare the result with what you expected.
# Example: Nested
# Run in the REPL or save as a .py file and execute with python.
for i in range(1, 4):
for j in range(1, 4):
print(i*j, end="\t")
print()
The program below demonstrates enumerate range. Read the comments on each line, run the code, then change names or values to see how the output shifts.
# for walks any iterable; range generates number sequences
for i in range(3): # 0,1,2
print("tick", i) # loop body
for n in range(2, 10, 2): # start, stop, step
print(n, end=" ") # 2 4 6 8
print() # newline after inline prints
items = ["pen", "book", "ink"] # cart lines
for index, item in enumerate(items, start=1): # human-friendly numbering
print(f"{index}. {item}") # 1. pen ...
total_chars = sum(len(x) for x in items) # generator inside sum
print(total_chars) # 3+4+3 = 10
This sample walks through zip parallel in a small, runnable script. Paste it into the REPL or save it as a .py file before you continue to the next block.
# zip pairs iterables element-wise for parallel iteration
names = ["Ada", "Grace"] # parallel column
scores = [99, 97] # second column
for name, score in zip(names, scores): # walk together
print(name, score) # Ada 99 ...
pairs = list(zip(names, scores)) # materialize tuples
print(pairs) # [('Ada',99), ...]
matrix = [[1, 2], [3, 4]] # 2x2 grid
for row in matrix: # outer loop
for value in row: # inner loop
print(value, end=" ") # row-major print
print() # finishing newline