Drop #7 – For Loops Made Simple
Few constructs in Python are as fundamental (and as elegant) as the for loop.
Whether you're iterating over a list of emails, processing log files, or building a custom parser, chances are you're looping through something. But writing loops that are both clear and Pythonic is a skill in itself.
Let’s explore the essentials, and some patterns you’ll want to master.
🔁 Basic Syntax
A typical for loop in Python looks like this:
names = ["Alice", "Bob", "Charlie"]
for name in names:
print(f"Hello, {name}!")
It’s simple and readable. But behind the scenes, this loop is powered by Python’s iterator protocol. It calls iter(names) to get an iterator and then repeatedly calls next() until StopIteration is raised.
Any iterable (not just lists) can be used in a for loop: strings, sets, dictionaries, file objects, and generators all work.
## 📏 Looping with range()
The range() function is a built-in tool for generating a sequence of numbers:
for i in range(5):
print(i)
This prints 0 to 4. That’s right: `range(n)` is exclusive of n. It’s a classic spot for off-by-one errors, especially if you're coming from other languages.
Want to customize the range?
for i in range(2, 10, 2):
print(i)
# Output: 2, 4, 6, 8
It works like range(start, stop, step). And yes, range() is lazy: it returns a range object, not a list.
🧠 Common Patterns to Know
1. Enumerate for Index + Value
names = ["Alice", "Bob", "Charlie"]
for idx, name in enumerate(names):
print(f"{idx}: {name}")
More readable and safer than manually managing an index.
2. Zip for Parallel Iteration
users = ["alice", "bob"]
emails = ["a@example.com", "b@example.com"]
for user, email in zip(users, emails):
print(f"{user} → {email}")
Stops at the shortest iterable. For strict equality in length, use itertools.zip_longest().
3. Looping Through Dictionaries
config = {"host": "localhost", "port": 8000}
for key, value in config.items():
print(f"{key}: {value}")
Always prefer .items() when you need both key and value.
4. Reversed and Sorted Loops
for x in reversed(range(3)):
print(x) # 2, 1, 0
for word in sorted(["banana", "apple", "cherry"]):
print(word) # apple, banana, cherry
Both reversed() and sorted() return iterables.
🧹 Loop Cleanups and Gotchas
- Avoid modifying a list while iterating over it. Instead, build a new list or use list comprehensions.
- Prefer for over while when you know the collection or range.
- Embrace list/set/dict comprehensions when your goal is to transform data, not just iterate over it.
- Python loops don’t need curly braces or manual iterators. Trust the protocol.
🧩 Your Turn
Which of these patterns do you use most?
What’s a common loop mistake you’ve seen in real projects?
👇 Let me know in the comments.
This was Drop #7 in the Python Drops series.
👉 Next up: while loops in Python — when you need full control, and how to use them without writing infinite loops by mistake.
Stay tuned! We're going deeper.
Senior Software Engineer | Python | Django | Applied AI Engineer
3wGreat drop. Python's loop syntax is one of its strengths, and tools like enumerate() and zip() really elevate readability. Looking forward to seeing the full set of tips in the article.
Software Engineer | Python, Django, AWS, RAG
3wThanks for sharing, Arthur
Goos job!! I’ll bookmark this one.
QA | Quality Assurance Engineer | SDET | Cypress | Selenium | RestAssured | Appium | CTFL | API Testing | Automation Framework
3wGreat content! Loved the focus on writing clean, Pythonic loops—enumerate() and zip() really make the difference in readability.