Python for Loops
The for loop in Python is used to iterate over a sequence (list, tuple, string, dictionary, set, or range). Unlike many other languages, Python's for loop is more like a "for each" loop.
Basic for Loop
python
# Iterate over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# apple
# banana
# cherry
# Iterate over a string
for char in "Python":
print(char, end=" ")
# P y t h o nThe range() Function
range() generates a sequence of numbers, commonly used for counting loops:
python
# range(stop) - 0 to stop-1
for i in range(5):
print(i, end=" ")
# 0 1 2 3 4
# range(start, stop) - start to stop-1
for i in range(2, 7):
print(i, end=" ")
# 2 3 4 5 6
# range(start, stop, step)
for i in range(0, 20, 3):
print(i, end=" ")
# 0 3 6 9 12 15 18
# Counting backwards
for i in range(10, 0, -1):
print(i, end=" ")
# 10 9 8 7 6 5 4 3 2 1
# Even numbers
for i in range(0, 11, 2):
print(i, end=" ")
# 0 2 4 6 8 10Iterating with enumerate()
Get both the index and value during iteration:
python
fruits = ["apple", "banana", "cherry", "date"]
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
# 0: apple
# 1: banana
# 2: cherry
# 3: date
# Custom starting index
for i, fruit in enumerate(fruits, start=1):
print(f"{i}. {fruit}")
# 1. apple
# 2. banana
# 3. cherry
# 4. dateIterating Over Dictionaries
python
student = {"name": "Alice", "age": 25, "grade": "A"}
# Iterate over keys (default)
for key in student:
print(key)
# name, age, grade
# Iterate over values
for value in student.values():
print(value)
# Alice, 25, A
# Iterate over key-value pairs
for key, value in student.items():
print(f"{key}: {value}")
# name: Alice
# age: 25
# grade: AIterating Over Multiple Sequences with zip()
python
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
cities = ["New York", "London", "Tokyo"]
for name, age, city in zip(names, ages, cities):
print(f"{name} ({age}) from {city}")
# Alice (25) from New York
# Bob (30) from London
# Charlie (35) from Tokyo
# Create a dictionary from two lists
keys = ["name", "age", "city"]
values = ["Alice", 25, "NYC"]
result = dict(zip(keys, values))
print(result) # {'name': 'Alice', 'age': 25, 'city': 'NYC'}
# zip stops at shortest sequence
a = [1, 2, 3, 4, 5]
b = ["a", "b", "c"]
for x, y in zip(a, b):
print(x, y)
# 1 a, 2 b, 3 cbreak, continue, and pass
break - Exit the Loop
python
# Find the first negative number
numbers = [3, 7, -1, 9, -5, 2]
for num in numbers:
if num < 0:
print(f"Found negative: {num}")
break
print(f"Checking: {num}")
# Checking: 3
# Checking: 7
# Found negative: -1continue - Skip to Next Iteration
python
# Print only even numbers
for i in range(10):
if i % 2 != 0:
continue
print(i, end=" ")
# 0 2 4 6 8pass - Do Nothing (Placeholder)
python
# Placeholder for future code
for i in range(5):
if i == 3:
pass # TODO: handle special case
print(i)The else Clause with for Loops
The else block runs when the loop completes without hitting a break:
python
# Search for a value
numbers = [1, 3, 5, 7, 9]
target = 4
for num in numbers:
if num == target:
print(f"Found {target}!")
break
else:
print(f"{target} not found in the list")
# 4 not found in the list
# Example: check if number is prime
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % 2 == 0:
return False
else:
return True
print(is_prime(17)) # True
print(is_prime(15)) # FalseNested for Loops
python
# Multiplication table
for i in range(1, 6):
for j in range(1, 6):
print(f"{i*j:4}", end="")
print()
# 1 2 3 4 5
# 2 4 6 8 10
# 3 6 9 12 15
# 4 8 12 16 20
# 5 10 15 20 25
# Pattern: right triangle
rows = 5
for i in range(1, rows + 1):
print("* " * i)
# *
# * *
# * * *
# * * * *
# * * * * *
# Flatten nested list
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = []
for row in matrix:
for num in row:
flat.append(num)
print(flat) # [1, 2, 3, 4, 5, 6, 7, 8, 9]Iterating with Unpacking
python
# List of tuples
students = [
("Alice", 90),
("Bob", 85),
("Charlie", 92)
]
for name, score in students:
print(f"{name}: {score}")
# With enumerate
for i, (name, score) in enumerate(students, 1):
print(f"{i}. {name} scored {score}")
# Nested dictionaries
school = {
"math": {"teacher": "Dr. Smith", "students": 30},
"science": {"teacher": "Dr. Jones", "students": 25}
}
for subject, details in school.items():
print(f"{subject}: {details['teacher']} ({details['students']} students)")Performance Tips
python
# Use range(len()) only when you need the index
# AVOID:
for i in range(len(fruits)):
print(fruits[i])
# PREFER:
for fruit in fruits:
print(fruit)
# If you need index, use enumerate:
for i, fruit in enumerate(fruits):
print(i, fruit)
# Avoid modifying a list while iterating over it
# WRONG:
numbers = [1, 2, 3, 4, 5]
# for num in numbers:
# if num % 2 == 0:
# numbers.remove(num) # Dangerous!
# CORRECT: iterate over a copy or use list comprehension
numbers = [num for num in numbers if num % 2 != 0]
print(numbers) # [1, 3, 5]Practical Example: Word Frequency Counter
python
"""
Count word frequency in a text.
"""
text = """
Python is great. Python is popular.
Python is used for web development and data science.
Many developers love Python.
"""
# Clean and split
words = text.lower().split()
# Count frequencies
frequency = {}
for word in words:
# Remove punctuation
word = word.strip(".,!?")
frequency[word] = frequency.get(word, 0) + 1
# Sort by frequency (descending)
sorted_words = sorted(frequency.items(), key=lambda x: x[1], reverse=True)
print("Word Frequency:")
print("-" * 25)
for word, count in sorted_words:
bar = "β" * count
print(f"{word:<15} {count:>2} {bar}")Summary
forloops iterate over any iterable (lists, strings, ranges, dicts, etc.)range(start, stop, step)generates number sequencesenumerate()gives index + value pairs during iterationzip()iterates over multiple sequences in parallelbreakexits the loop,continueskips to next iteration- The
elseclause on a loop runs when nobreakoccurs - Avoid modifying a collection while iterating over it
- Prefer direct iteration and
enumerate()overrange(len())
Next, we'll learn about Python while loops.