Python for Loop
The for loop is Python's most-used iteration tool — it lets
you visit every item in any sequence or iterable without needing an index counter. From
processing a list of names to reading a file line-by-line,
for loops power nearly every Python program. This chapter
covers the complete toolbox: range(),
enumerate(), zip(),
nested loops, break,
continue, else on loops,
and the elegant list comprehension syntax.
What is a for Loop?
A for loop iterates over an iterable — any object that can return its
elements one at a time. Lists, strings, tuples, dicts, sets, files, and any object with an
__iter__() method qualify. For each item, Python executes
the loop body exactly once, automatically advancing to the next element.
Unlike languages where you manually manage an index counter, Python's
for loop abstracts that away — you work directly with the
values. This makes Python loops concise, readable, and far less error-prone than C-style
for(int i=0; i<n; i++) loops.
range(), file objects, and generators. Python calls
iter() on it to get an iterator, then repeatedly calls
next() until
StopIteration is raised.
Iterating Sequences — Lists, Strings, Tuples, Dicts
The for loop works identically on all Python sequences. The
loop variable takes on each element's value one at a time, and the indented block runs once per
element. You can use any valid variable name as the loop variable.
# Iterating a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# apple
# banana
# cherry
# Iterating a string — character by character
for ch in "Python":
print(ch, end="-") # P-y-t-h-o-n-
print()
# Iterating a tuple
coords = (10, 20, 30)
for val in coords:
print(val * 2, end=" ") # 20 40 60
print()
# Iterating a dict — keys by default
person = {"name": "Alice", "age": 25, "city": "Vadodara"}
for key in person:
print(key) # name age city
for val in person.values():
print(val) # Alice 25 Vadodara
for k, v in person.items():
print(f"{k}: {v}") # name: Alice age: 25 city: Vadodara
# Iterating a set (unordered — no guaranteed order)
unique = {"red", "green", "blue"}
for color in unique:
print(color)
# Tuple unpacking in loops — common and elegant
pairs = [("Alice", 90), ("Bob", 85), ("Carol", 92)]
for name, score in pairs:
print(f"{name}: {score}")
x. The
colon and 4-space indentation are mandatory — same rules as
if.
for k, v in d.items() — the most Pythonic way to
iterate a dict.
end parameter replaces the default newline.
Useful for printing on a single line inside a loop.
The range() Function
range() generates a sequence of integers on demand — it's
lazy, creating only one number at a time rather than storing all in memory. It
is the standard way to repeat something a fixed number of times or to produce index-based loops
when needed.
# range(stop) — 0 to stop-1
for i in range(5):
print(i, end=" ") # 0 1 2 3 4
print()
# range(start, stop) — start to stop-1
for i in range(2, 7):
print(i, end=" ") # 2 3 4 5 6
print()
# range(start, stop, step)
for i in range(0, 20, 5):
print(i, end=" ") # 0 5 10 15
print()
# Negative step — counting down
for i in range(10, 0, -2):
print(i, end=" ") # 10 8 6 4 2
print()
# range is lazy — convert to list to see all values
print(list(range(1, 11))) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Repeat something N times
for _ in range(3):
print("Hello!") # Hello! × 3
# Sum of 1 to 100
total = 0
for n in range(1, 101):
total += n
print(total) # 5050
# Index-based access with range + len
items = ["a", "b", "c"]
for i in range(len(items)):
print(f"items[{i}] = {items[i]}")
# Prefer enumerate() over this pattern
| Call | Sequence Generated | Notes |
|---|---|---|
range(5) |
0, 1, 2, 3, 4 | Default start=0, step=1 |
range(2, 8) |
2, 3, 4, 5, 6, 7 | stop is exclusive |
range(0, 10, 2) |
0, 2, 4, 6, 8 | Even numbers |
range(10, 0, -1) |
10, 9, 8, …, 1 | Countdown |
range(0) |
(empty) | No iterations |
enumerate() and zip()
Two built-in functions make for loops dramatically more
powerful. enumerate() adds an automatic counter to any
iterable — eliminating the need for range(len(...)).
zip() combines multiple iterables in parallel — iterating
over two or more sequences simultaneously with ease.
# enumerate() — index + value together
fruits = ["apple", "banana", "cherry"]
for i, fruit in enumerate(fruits):
print(f"{i}: {fruit}")
# 0: apple
# 1: banana
# 2: cherry
# Custom start index
for i, fruit in enumerate(fruits, start=1):
print(f"{i}. {fruit}")
# 1. apple 2. banana 3. cherry
# zip() — iterate two lists in parallel
names = ["Alice", "Bob", "Carol"]
scores = [90, 85, 92 ]
for name, score in zip(names, scores):
print(f"{name}: {score}")
# Alice: 90 Bob: 85 Carol: 92
# zip with three lists
cities = ["Vadodara", "Mumbai", "Delhi"]
for n, s, c in zip(names, scores, cities):
print(f"{n} ({c}): {s}")
# zip stops at the shortest iterable
print(list(zip([1,2,3], ["a","b"])))
# [(1, 'a'), (2, 'b')] — 3 is dropped
# Create a dict from two lists with zip
student_dict = dict(zip(names, scores))
print(student_dict)
# {'Alice': 90, 'Bob': 85, 'Carol': 92}
# Combining enumerate + zip
for i, (n, s) in enumerate(zip(names, scores), 1):
print(f"#{i} {n}: {s}")
# #1 Alice: 90 #2 Bob: 85 #3 Carol: 92
for i in range(len(items)): and then accessing
items[i] is un-Pythonic. Use
for i, item in enumerate(items): instead — it's cleaner,
faster, and avoids off-by-one index bugs.
Nested for Loops & Loop else
A nested loop is a loop inside another loop. For every single iteration of the
outer loop, the inner loop runs completely. Common use cases include matrix operations,
generating combinations, and building 2D data structures. Python also has a unique
else clause on loops — it runs when the loop finishes
normally (not via break).
# Multiplication table
for i in range(1, 4):
for j in range(1, 4):
print(f"{i}×{j}={i*j}", end=" ")
print()
# 1×1=1 1×2=2 1×3=3
# 2×1=2 2×2=4 2×3=6
# 3×1=3 3×2=6 3×3=9
# 2D list (matrix) iteration
matrix = [[1,2,3], [4,5,6], [7,8,9]]
for row in matrix:
for cell in row:
print(cell, end=" ")
print()
# 1 2 3
# 4 5 6
# 7 8 9
# for...else — else runs only if loop completed without break
numbers = [1, 3, 5, 7]
for n in numbers:
if n % 2 == 0:
print(f"Found even: {n}")
break
else:
print("No even numbers found") # runs — no break triggered
# Prime checker using for...else
def is_prime(n):
if n < 2: return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False # divisor found — not prime
return True # no divisor — is prime
print(is_prime(17)) # True
print(is_prime(15)) # False
break, continue & pass
Python provides three statements to control loop flow:
break exits the loop immediately,
continue skips the rest of the current iteration and jumps
to the next, and pass does nothing (a syntactic
placeholder). Together they give you fine-grained control over iteration.
# break — exit the loop immediately
for n in range(10):
if n == 5:
break
print(n, end=" ") # 0 1 2 3 4
print()
# Real-world: search — stop when found
users = ["alice", "bob", "carol"]
target = "bob"
for user in users:
if user == target:
print(f"Found: {user}")
break # no need to keep looping
# continue — skip current iteration, carry on with next
for n in range(10):
if n % 2 == 0:
continue # skip even numbers
print(n, end=" ") # 1 3 5 7 9
print()
# Real-world: skip empty / invalid items
data = ["Alice", "", "Bob", None, "Carol"]
for item in data:
if not item:
continue # skip falsy values
print(item.upper()) # ALICE BOB CAROL
# pass — syntactic placeholder (does nothing)
for i in range(5):
pass # loop body required by syntax; TODO later
# break in nested loops — only breaks the INNER loop
for i in range(1, 4):
for j in range(1, 4):
if j == 2:
break # only exits inner loop
print(f"({i},{j})", end=" ")
print()
# (1,1) (2,1) (3,1)
| Statement | Effect | Loop else runs? |
|---|---|---|
break |
Exits the loop immediately |
|
continue |
Skips to the next iteration |
|
pass |
Does nothing — placeholder |
|
List, Dict & Set Comprehensions
Comprehensions condense a for loop that
builds a collection into a single readable line. They are faster than equivalent loops (compiled
to optimised bytecode), and they communicate intent directly — "build a list of X for
each Y in Z". Python supports list, dict, set, and generator comprehensions.
# ── List comprehension ──────────────────────────────
# Syntax: [expression for item in iterable if condition]
# Squares 1–10
squares = [x**2 for x in range(1, 11)]
print(squares)
# [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
# Filter: only even numbers
evens = [x for x in range(1, 21) if x % 2 == 0]
print(evens)
# [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
# Transform: uppercase all strings
words = ["hello", "world", "python"]
upper = [w.upper() for w in words]
print(upper) # ['HELLO', 'WORLD', 'PYTHON']
# Nested comprehension — flatten a matrix
matrix = [[1,2,3],[4,5,6],[7,8,9]]
flat = [n for row in matrix for n in row]
print(flat) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
# ── Dict comprehension ──────────────────────────────
# Syntax: {key: value for item in iterable}
sq_dict = {x: x**2 for x in range(1, 6)}
print(sq_dict)
# {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# Invert a dictionary
original = {"a":1, "b":2, "c":3}
inverted = {v: k for k, v in original.items()}
print(inverted) # {1: 'a', 2: 'b', 3: 'c'}
# ── Set comprehension ───────────────────────────────
nums = [1, 2, 2, 3, 3, 4]
unique_squares = {x**2 for x in nums}
print(unique_squares) # {1, 4, 9, 16} — duplicates removed
# ── Generator expression ────────────────────────────
# Like list comprehension but lazy — uses () instead of []
gen = (x**2 for x in range(1, 1000000)) # no memory used yet
print(next(gen)) # 1 — computed on demand
print(sum(x for x in range(101))) # 5050 — efficient sum
for loop when you need multiple statements,
complex logic, or when side effects (printing, writing to a file) are the purpose —
comprehensions should never have side effects.
Practice Python Online — Free Compilers
Don't want to install anything yet? Practice all for loop examples from this chapter directly in your browser with these free Python environments.
- The for loop iterates over any iterable — lists, strings, tuples, dicts, sets, files, and range objects.
-
range(start, stop, step) generates integers lazily.
range(5)→ 0–4; negative step counts down; stop is always exclusive. -
enumerate(iterable, start=0) yields
(index, value)pairs. Always prefer it overrange(len(...))for index+value access. -
zip(a, b, ...) pairs elements from multiple iterables. Stops at the
shortest. Use
dict(zip(keys, values))to build dicts. - Nested loops: the inner loop runs fully for each outer iteration. Use them for matrices and combination problems.
- break exits the loop; continue skips the rest of the current iteration; pass is a no-op placeholder.
-
A for...else clause runs only when the loop finishes without hitting
break— useful for search patterns. -
List comprehension:
[expr for x in iterable if condition]— faster and more readable than an equivalent loop for building collections. -
Dict/Set comprehensions follow the same pattern. Generator expressions
(expr for ...)are lazy — ideal for large sequences.
range(2, 10, 3) produces the sequence
2, 5, 8. Here's why: it starts at
2 (the start), increments by
3 (the step) each time, and stops
before reaching 10 (the stop,
exclusive).
- 2 → 2 + 3 = 5 (still < 10, include it)
- 5 → 5 + 3 = 8 (still < 10, include it)
- 8 → 8 + 3 = 11 (≥ 10, stop)
Converting to list: list(range(2, 10, 3)) →
[2, 5, 8]
range(len(items)) generates indices, and
then you must use items[i] to get values —
two operations where one would suffice. It's also more error-prone (off-by-one
bugs, extra variable).
enumerate(items) directly yields
(index, value) tuples in one step:
# ❌ Verbose, error-prone
for i in range(len(items)):
print(i, items[i])
# ✅ Pythonic, clean
for i, item in enumerate(items):
print(i, item)
enumerate() also works with any iterable
(generators, files) not just lists, and accepts a
start parameter for custom numbering.
break completely exits the loop — no more iterations happen, and the program continues with code after the loop. continue skips only the rest of the current iteration — the loop variable advances to the next item and the body runs again from the top.
for i in range(5):
if i == 3: break
print(i) # 0 1 2 (stops at 3)
for i in range(5):
if i == 3: continue
print(i) # 0 1 2 4 (skips 3)
The else clause of a
for loop executes when the loop
finishes all its iterations normally — i.e., without being
interrupted by a break statement. If
break exits the loop, the
else block is skipped entirely. The most
common use case is a search pattern: loop to search for an
item, break if found, and use
else to handle "not found":
for item in data:
if is_match(item):
process(item)
break
else:
print("No match found") # runs only if break never hit
A list comprehension uses square brackets
[...] and immediately computes and stores
all values in memory as a list. A
generator expression uses parentheses
(...) and is lazy — it produces one
value at a time on demand without storing the full sequence.
-
[x**2 for x in range(1000000)]— builds a list of 1M integers in RAM immediately (~8 MB) -
(x**2 for x in range(1000000))— a generator; each value computed only when requested (~100 bytes) -
Use list comprehension when you need the full list (random access, multiple
passes). Use generator expressions when you just iterate once or pass to
sum(),max(),any(), etc.
list(range(1, 10, 3)) return?
[x*2 for x in range(5) if x % 2 == 0]?
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.