Loops
Loops allow you to process collections of data or run a code block multiple times.
The Python for loop is designed to iterate directly over iterables and perform an action on each item. Clear and direct for loops should communicate what you’re iterating over and why. They should also help you avoid getting lost in counters and indexing.
On the other hand, while loops allow you to repeat a code block multiple times as long as a condition remains true. They’re useful when the number of iterations isn’t known up front or depends on some changing state, such as user input, input/output (I/O), or similar.
When you’re writing loops, keep the following best practices in mind:
- Iterate directly over iterable objects. Write loops like
for item in items:instead offor i in range(len(items)):. This is clearer, less error-prone, and works with any iterable, not just sequences. - Use
enumerate()when you need indices. Use the built-inenumerate()function to iterate over both index and value instead of using a counter or writing something likefor i in range(len(items)):. - Use
zip()for parallel iteration over multiple iterables. Use the built-inzip()function to pair elements when you need to loop over multiple iterables at the same time, rather than juggling multiple indices. This practice leads to clearer, more Pythonic loops. - Prefer
forloops when iterating over collections. Use the Pythonforloop when you know the sequence of values you want to process, such as items in a list or lines in a file. Reservewhilefor cases where the number of iterations depends on a changing condition. - Keep
whileloop conditions clear and ensure the updating logic is correct. Make it clear how the loop condition will eventually become false by updating the relevant state inside the loop. Usewhile Trueonly when it improves clarity, and pair it with explicitbreakstatements. - Avoid repeated string concatenation in loops. Building strings with
+=inside a loop is inefficient. Use.join()or tools likeio.StringIOwhen you need to accumulate many small pieces into a single string.
To see some of these best practices in action, consider the following example:
🔴 Avoid this:
>>> items = ["apple", "banana", "cherry"]
>>> labeled = []
>>> i = 0
>>> while i < len(items):
... labeled.append(f"{i}: {items[i].upper()}")
... i += 1
...
>>> labeled
['0: APPLE', '1: BANANA', '2: CHERRY']
This code works, but manual index management is harder to read and easier to get wrong.
✅ Favor this:
>>> items = ["apple", "banana", "cherry"]
>>> labeled = []
>>> for index, item in enumerate(items):
... labeled.append(f"{index}: {item.upper()}")
...
>>> labeled
['0: APPLE', '1: BANANA', '2: CHERRY']
In this version, enumerate() provides both the index and value, and the for loop reads clearly. The result is shorter and easier to maintain.
Related Resources
Tutorial
Python for Loops: The Pythonic Way
In this tutorial, you'll learn all about the Python for loop. You'll learn how to use this loop to iterate over built-in data types, such as lists, tuples, strings, and dictionaries. You'll also explore some Pythonic looping techniques and much more.
For additional information on related topics, take a look at the following resources:
- Python while Loops: Repeating Tasks Conditionally (Tutorial)
- How Can You Emulate Do-While Loops in Python? (Tutorial)
- Skip Ahead in Loops With Python's continue Keyword (Tutorial)
- Nested Loops in Python (Tutorial)
- Python enumerate(): Simplify Loops That Need Counters (Tutorial)
- How to Exit Loops Early With the Python break Keyword (Tutorial)
- When to Use a List Comprehension in Python (Tutorial)
- Python Dictionary Comprehensions: How and When to Use Them (Tutorial)
- Python Set Comprehensions: How and When to Use Them (Tutorial)
- For Loops in Python (Definite Iteration) (Course)
- Python for Loops: The Pythonic Way (Quiz)
- Mastering While Loops (Course)
- Python while Loops: Repeating Tasks Conditionally (Quiz)
- Skip Ahead in Loops With Python's continue Keyword (Quiz)
- Nested Loops in Python (Quiz)
- Looping With Python enumerate() (Course)
- Python's enumerate() (Quiz)
- Break Out of Loops With Python's break Keyword (Course)
- How to Exit Loops Early With the Python break Keyword (Quiz)
- Understanding Python List Comprehensions (Course)
- When to Use a List Comprehension in Python (Quiz)
- Building Dictionary Comprehensions in Python (Course)
- Python Dictionary Comprehensions: How and When to Use Them (Quiz)
- Python Set Comprehensions: How and When to Use Them (Quiz)