Loops are how we automate repetition in code. But beyond just for and while, Python gives us powerful built-in tools like enumerate(), zip(), and the entire itertools module for smarter, cleaner, and more powerful iterations.
In this post, you’ll learn:
- All about
forandwhileloops (with deeper examples) - How to iterate with
enumerate()andzip() - What
range()actually does and why it’s so powerful - Why
itertoolsis a hidden gem for developers - Real-world scenarios like combinations, counters, and grouped data
🔁 Revisiting the Basics: for and while
for Loop Recap:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I like {fruit}")while Loop Recap:
count = 0
while count < 3:
print("Count is:", count)
count += 1🔍 The range() Function (Super Useful)
Syntax:
range(start, stop, step)start: where to begin (default = 0)stop: where to end (not included)step: how much to increase by (default = 1)
Examples:
for i in range(5): # 0 to 4
print(i)
for i in range(1, 6): # 1 to 5
print(i)
for i in range(10, 0, -2): # Countdown by 2s
print(i)📍 enumerate() Loop with Index
names = ["Ali", "Fatima", "Sara"]
for index, name in enumerate(names):
print(f"{index}: {name}")Output:
0: Ali
1: Fatima
2: Sara
🔗 zip() Loop Through Multiple Lists
students = ["Ali", "Fatima", "Sara"]
marks = [88, 92, 77]
for name, mark in zip(students, marks):
print(f"{name} scored {mark}")Output:
Ali scored 88
Fatima scored 92
Sara scored 77
✅ Tip:
If lists are of unequal length, zip() stops at the shortest one.
📚 Introducing itertools – Python’s Loop Power Tools
itertools is a standard Python module that provides functions to:
- Create infinite or advanced iterators
- Work with combinations, permutations, grouping
- Chain or filter multiple iterable sources
✅ Importing It:
import itertools🔄 itertools.count() – Infinite Counter
from itertools import count
for num in count(5):
if num > 10:
break
print(num)Output:
5
6
7
8
9
10
♾️ itertools.cycle() – Loop Forever Through a List
from itertools import cycle
colors = ["red", "green", "blue"]
for color in cycle(colors):
print(color)
# Use break or limit it!Use with caution it’s infinite by default.
📦 itertools.chain() – Combine Multiple Lists
from itertools import chain
a = [1, 2]
b = [3, 4]
for item in chain(a, b):
print(item)Output:
1 2 3 4
🔢 itertools.combinations() – Pick Unique Pairs
from itertools import combinations
players = ["Ali", "Fatima", "Sara"]
for combo in combinations(players, 2):
print(combo)Output:
(‘Ali’, ‘Fatima’)
(‘Ali’, ‘Sara’)
(‘Fatima’, ‘Sara’)
🔁 itertools.permutations() – All Possible Orders
from itertools import permutations
for p in permutations([1, 2, 3]):
print(p)Output:
All 6 possible orderings of [1, 2, 3]
🧮 itertools.groupby() – Group Consecutive Data
from itertools import groupby
data = [1, 1, 2, 2, 2, 3, 1, 1]
for key, group in groupby(data):
print(key, list(group))Output:
1 [1, 1]2 [2, 2, 2]
3 [3]
1 [1, 1]
📌 Want to go beyond loops and try a cleaner, functional style?
Read our post on Functional Programming in Python to learn how to use map(), filter(), lambda, and generators.
⚠️ Common Looping Mistakes
| Mistake | Fix |
|---|---|
Forgetting break in infinite loop | Always use break in while True or itertools.count() |
| Misusing zip with unequal lists | Use zip_longest() if needed from itertools |
| Using for/while when list comp is better | Choose simple list comprehension for short logic |