Python For Loops: Complete Tutorial with Examples
For loops are fundamental to Python programming. Here's everything you need to know to use them effectively:
1. Basic For Loop Syntax
# Iterate over a list
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
# Iterate over a string
for char in "Python":
print(char) # P, y, t, h, o, n
# Iterate over a tuple
coordinates = (10, 20, 30)
for coord in coordinates:
print(coord)
2. Using range() Function
# range(stop) - from 0 to stop-1
for i in range(5):
print(i) # 0, 1, 2, 3, 4
# range(start, stop) - from start to stop-1
for i in range(2, 8):
print(i) # 2, 3, 4, 5, 6, 7
# range(start, stop, step) - with step increment
for i in range(0, 10, 2):
print(i) # 0, 2, 4, 6, 8
# Reverse range
for i in range(10, 0, -1):
print(i) # 10, 9, 8, ..., 1
3. enumerate() - Get Index and Value
# 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
# Start index at 1 instead of 0
for index, fruit in enumerate(fruits, start=1):
print(f"{index}. {fruit}")
# 1. apple
# 2. banana
# 3. cherry
4. Iterate Over Dictionaries
person = {'name': 'Alice', 'age': 30, 'city': 'NYC'}
# Iterate over keys (default)
for key in person:
print(key) # name, age, city
# Iterate over values
for value in person.values():
print(value) # Alice, 30, NYC
# Iterate over key-value pairs ✅ (most common)
for key, value in person.items():
print(f"{key}: {value}")
# name: Alice
# age: 30
# city: NYC
5. Nested For Loops
# Create a multiplication table
for i in range(1, 6):
for j in range(1, 6):
print(f"{i} x {j} = {i*j}")
# Iterate over 2D list (matrix)
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
for row in matrix:
for num in row:
print(num, end=' ')
print() # New line after each row
# Flatten 2D list
flat = [num for row in matrix for num in row]
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
6. Loop Control: break and continue
# break - exit loop early
for i in range(10):
if i == 5:
break # Stop loop when i is 5
print(i) # 0, 1, 2, 3, 4
# continue - skip current iteration
for i in range(10):
if i % 2 == 0:
continue # Skip even numbers
print(i) # 1, 3, 5, 7, 9
# Find first match
numbers = [1, 3, 5, 8, 9, 11]
for num in numbers:
if num % 2 == 0:
print(f"First even number: {num}")
break
7. Loop with else Clause
# else runs if loop completes without break
numbers = [1, 3, 5, 7, 9]
for num in numbers:
if num % 2 == 0:
print("Found even number")
break
else:
print("No even numbers found") # This runs
# Practical example: Search for item
items = ['apple', 'banana', 'cherry']
search = 'grape'
for item in items:
if item == search:
print(f"Found {search}")
break
else:
print(f"{search} not found")
8. zip() - Iterate Multiple Lists
# Iterate two lists together
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(f"{name} is {age} years old")
# Zip three lists
cities = ['NYC', 'LA', 'Chicago']
for name, age, city in zip(names, ages, cities):
print(f"{name}, {age}, lives in {city}")
# Create dictionary from two lists
person_dict = dict(zip(names, ages))
# {'Alice': 25, 'Bob': 30, 'Charlie': 35}
9. Practical Examples
# Sum all numbers
numbers = [1, 2, 3, 4, 5]
total = 0
for num in numbers:
total += num
print(total) # 15
# Count occurrences
text = "hello world"
count = 0
for char in text:
if char == 'l':
count += 1
print(count) # 3
# Filter list
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = []
for num in numbers:
if num % 2 == 0:
evens.append(num)
# Better: Use list comprehension ✅
evens = [num for num in numbers if num % 2 == 0]
# Process files
import os
for filename in os.listdir('.'):
if filename.endswith('.txt'):
print(f"Processing {filename}")
Best Practices
- ✅ Use
enumerate()when you need both index and value - ✅ Use
zip()to iterate multiple lists together - ✅ Use
range()only when you need numeric indices - ✅ Use list comprehensions for simple transformations (faster)
- ✅ Use
breakto exit early and save computation - ❌ Don't modify list while iterating over it (make a copy first)
- ❌ Don't use
for i in range(len(list))- iterate directly - ⚠️ Avoid deeply nested loops (more than 3 levels) - refactor into functions
Pro Tip: Instead of for i in range(len(items)): item = items[i], simply use for item in items:. It's more Pythonic, cleaner, and faster. Use enumerate() if you need the index!