for
Updated March 16, 2026 · Keywords
keyword loop iteration control-flow
The for keyword iterates over sequences in Python. It’s the primary way to loop through collections, strings, ranges, and other iterables.
Syntax
for variable in iterable:
# Loop body
Basic Examples
Iterating Over a List
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# apple
# banana
# cherry
Iterating Over a String
for char in "Python":
print(char)
# P
# y
# t
# h
# o
# n
Using range()
for i in range(5):
print(i)
# 0
# 1
# 2
# 3
# 4
Using the Index
enumerate()
Get both index and value:
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
# 0: apple
# 1: banana
# 2: cherry
Starting Index
for index, fruit in enumerate(fruits, start=1):
print(f"{index}: {fruit}")
# 1: apple
# 2: banana
# 3: cherry
Iterating Over Dictionaries
Keys Only
person = {"name": "Alice", "age": 30, "city": "NYC"}
for key in person:
print(key)
# name
# age
# city
Key-Value Pairs
for key, value in person.items():
print(f"{key}: {value}")
# name: Alice
# age: 30
# city: NYC
The else Clause
Runs after the loop completes normally:
for i in range(3):
print(i)
else:
print("Loop completed!")
# 0
# 1
# 2
# Loop completed!
The else block doesn’t run if you break out of the loop:
for i in range(5):
if i == 3:
break
print(i)
else:
print("Loop completed!")
# 0
# 1
# 2
Nested Loops
matrix = [[1, 2], [3, 4], [5, 6]]
for row in matrix:
for num in row:
print(num, end=" ")
print()
# 1 2
# 3 4
# 5 6
List Comprehension Alternative
For simple transformations, consider list comprehensions:
# Traditional loop
squares = []
for i in range(5):
squares.append(i ** 2)
# List comprehension
squares = [i ** 2 for i in range(5)]
Breaking and Continuing
break - Exit Loop Early
fruits = ["apple", "banana", "cherry", "date"]
for fruit in fruits:
if fruit == "cherry":
break
print(fruit)
# apple
# banana
continue - Skip Current Iteration
for i in range(5):
if i == 2:
continue
print(i)
# 0
# 1
# 3
# 4
Best Practices
Use enumerate Instead of range(len())
# Avoid
for i in range(len(fruits)):
print(fruits[i])
# Prefer
for fruit in enumerate(fruits):
print(f"{i}: {fruit}")
Choose the Right Iteration Method
| Task | Use |
|---|---|
| Process each item | for item in iterable |
| Need index and value | enumerate() |
| Key-value pairs | .items() |
| Fixed count | range(n) |
Keep Loops Simple
Extract complex logic into helper functions:
# Avoid deeply nested loops
# Extract logic into functions when possible
Common Patterns
Finding an Item
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
if fruit.startswith("b"):
print(f"Found: {fruit}")
break
# Found: banana
Aggregating Values
numbers = [1, 2, 3, 4, 5]
total = 0
for num in numbers:
total += num
print(total)
# 15
Filtering Items
numbers = [1, 2, 3, 4, 5, 6]
evens = []
for num in numbers:
if num % 2 == 0:
evens.append(num)
print(evens)
# [2, 4, 6]
See Also
- break keyword — exit loops early
- continue keyword — skip iterations
- range built-in — generate number sequences
- enumerate built-in — get index and value