Python — For Loops
Basic For Loop
for item in [1, 2, 3]:
print(item)
# Output:
# 1
# 2
# 3
Looping Over Different Types
Strings
for char in "Hello":
print(char)
# H, e, l, l, o
Lists
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Tuples
colors = ("red", "green", "blue")
for color in colors:
print(color)
Dictionaries
person = {"name": "Alice", "age": 25}
for key in person:
print(f"{key}: {person[key]}")
# Using items()
for key, value in person.items():
print(f"{key}: {value}")
Sets
unique = {1, 2, 3, 4, 5}
for num in unique:
print(num)
range() Function
# range(stop)
for i in range(5):
print(i) # 0, 1, 2, 3, 4
# range(start, stop)
for i in range(1, 6):
print(i) # 1, 2, 3, 4, 5
# range(start, stop, step)
for i in range(0, 10, 2):
print(i) # 0, 2, 4, 6, 8
# Countdown
for i in range(10, 0, -1):
print(i) # 10, 9, 8, ..., 1
enumerate()
Get index and value together:
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
# 0: apple
# 1: banana
# 2: cherry
# Start from 1
for i, fruit in enumerate(fruits, start=1):
print(f"{i}. {fruit}")
# 1. apple
# 2. banana
# 3. cherry
zip()
Loop over multiple lists simultaneously:
names = ["Alice", "Bob", "Charlie"]
scores = [95, 87, 92]
for name, score in zip(names, scores):
print(f"{name}: {score}")
# Alice: 95
# Bob: 87
# Charlie: 92
Nested Loops
# Multiplication table
for i in range(1, 4):
for j in range(1, 4):
print(f"{i} x {j} = {i*j}")
# Loop through 2D list
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
for cell in row:
print(cell, end=" ")
print()
break, continue, else
# break — exit loop early
for num in range(10):
if num == 5:
break
print(num) # 0, 1, 2, 3, 4
# continue — skip to next iteration
for num in range(10):
if num % 2 == 0:
continue
print(num) # 1, 3, 5, 7, 9
# else — runs if loop completes without break
for num in range(10):
if num == 15:
break
else:
print("15 not found") # This runs
List Comprehensions (Concise Loops)
# Instead of:
squares = []
for x in range(10):
squares.append(x**2)
# Write:
squares = [x**2 for x in range(10)]
# With condition
evens = [x for x in range(20) if x % 2 == 0]
Practical Examples
# Sum of numbers
total = 0
for num in [1, 2, 3, 4, 5]:
total += num
print(total) # 15
# Find maximum
numbers = [23, 45, 12, 67, 34]
max_val = numbers[0]
for num in numbers:
if num > max_val:
max_val = num
print(max_val) # 67
# Count occurrences
text = "hello world"
count = 0
for char in text:
if char == 'l':
count += 1
print(count) # 3
Best Practices
- Use
enumerate()instead of manual index tracking - Use
zip()for parallel iteration - Keep loops simple — extract complex logic into functions
- Use list comprehensions for simple transformations
- Avoid modifying a list while iterating over it
Mini Practice
- Print numbers 1-20 using
range() - Loop through a dictionary and print key-value pairs
- Use
enumerate()to number a list of items - Use
zip()to combine two lists - Write a nested loop to print a multiplication table
Up Next
Next: While Loops →
Related Topics
Frequently Asked Questions about For Loops
What is For Loops in Python?
For Loops is a fundamental concept in Python. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn For Loops?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn For Loops.
Why is For Loops important in Python?
For Loops is essential for Python development. Understanding this concept will help you write better code and solve real-world problems more effectively.