Python for Loops – Mastering Iteration the Pythonic Way
Last updated 6 months, 4 weeks ago | 562 views 75 5
Loops are essential in any programming language. Python’s for loop is simple yet incredibly powerful, allowing you to iterate over lists, strings, dictionaries, sets, and more with elegant syntax.
This guide will cover:
-
What
forloops are and how they work -
Looping over different data types
-
Using
range() -
Nested loops
-
Controlling loops with
breakandcontinue -
Tips and common pitfalls
-
A complete example
✅ What Is a for Loop?
A for loop in Python is used to iterate over a sequence (like a list, tuple, dictionary, set, or string).
Syntax
for variable in sequence:
# code block
-
variable: Temporary placeholder for each item in the sequence. -
sequence: A collection of items to loop through.
Example 1: Looping Over a List
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
Example 2: Looping Over a String
for char in "Python":
print(char)
Example 3: Using range()
range() generates a sequence of numbers, which is often used for looping a specific number of times.
for i in range(5):
print(i)
Output:
0
1
2
3
4
range(5)produces numbers from 0 to 4 (not inclusive of 5).
range(start, stop, step) Example
for i in range(1, 10, 2):
print(i)
Output:
1
3
5
7
9
Example 4: Looping Over a Dictionary
student = {"name": "Alice", "age": 20, "grade": "A"}
for key, value in student.items():
print(f"{key}: {value}")
Example 5: Looping Over a Set or Tuple
colors = {"red", "green", "blue"}
for color in colors:
print(color)
Note: Sets are unordered, so output order may vary.
Nested for Loops
A loop inside another loop.
for i in range(1, 4):
for j in range(1, 4):
print(f"{i} * {j} = {i*j}")
Exiting Loops Early – break
for i in range(5):
if i == 3:
break
print(i)
Output:
0
1
2
Skipping Iterations – continue
for i in range(5):
if i == 2:
continue
print(i)
Output:
0
1
3
4
➕ The else Clause
Python’s for loops can have an else block, which executes only if the loop completes without a break.
for i in range(3):
print(i)
else:
print("Loop completed successfully!")
Common Pitfalls
| Pitfall | Cause | Solution |
|---|---|---|
Forgetting : |
SyntaxError | Always use a colon after for |
| Modifying the list while looping | Unexpected results | Loop over a copy if modifying |
| Assuming order in sets/dicts | Sets/dicts are unordered | Use sorted() if order is needed |
Using = instead of == |
Assignment instead of comparison in if |
Use == for condition checks |
Tips and Best Practices
-
Use
enumerate()to get index and value:for index, value in enumerate(["a", "b", "c"]): print(index, value) -
Use
zip()to loop over multiple lists together:names = ["Alice", "Bob"] scores = [85, 90] for name, score in zip(names, scores): print(f"{name} scored {score}") -
Use
reversed()andsorted()with any iterable:for num in reversed(range(5)): print(num)
Complete Example: Multiplication Table
for i in range(1, 6):
for j in range(1, 6):
print(f"{i * j:2}", end=" ")
print()
Output:
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
What’s Next?
After learning for loops, you can explore:
-
Comprehensions: List/set/dictionary comprehensions using
for -
Generators and iterators
-
Looping through files or API results
-
Combining with
ifconditions inside loops
Practice Challenge
Task: Write a program that finds the factorial of a given number using a for loop.
num = int(input("Enter a number: "))
factorial = 1
for i in range(1, num + 1):
factorial *= i
print("Factorial is", factorial)