For & While Loops
Master iteration in Python through for and while loops, index-free enumeration, early loop exits, and Python's unique for-else clause.
The Python Iteration Protocol
In Python, for loops do not use the classic C-style index counter (for (int i=0; i<n; i++)). Instead, Python's for loop iterates directly over any iterable object - such as lists, strings, tuples, dictionaries, or generators - fetching elements one by one.
A while loop repeatedly executes its block as long as its condition remains truthy. It is primarily used when the number of iterations is unknown in advance, such as polling a connection or processing a queue.
The Power of for ... else
Python provides a distinctive feature rarely found in other languages: an else block attached directly to a for or while loop.
The else clause executes if and only if the loop finishes all iterations naturally, without encountering a break statement.
This pattern eliminates the need for messy boolean flag variables (such as found = False) when searching for an item in a sequence.
Loop Control: break, continue & enumerate
The break statement immediately terminates the loop and jumps execution past the entire loop construct, bypassing any else block.
The continue statement skips the remainder of the current iteration and jumps directly to the next cycle.
When you need both the zero-based index and the element itself, never iterate over range(len(items)). Use the built-in enumerate(items) function: for index, item in enumerate(items):.
The Iteration Stepper & Else Gate
Step through a loop item by item. Test what happens to the trailing else block when the loop completes naturally versus when a break is triggered early.
Python Pattern: Use for ... else instead of messy boolean flags (like found = False). If the search ends without a break, the else clause executes the fallback cleanly.
Python for loops iterate directly over items. The trailing else block executes only if the loop runs to natural completion without a break.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- Python for loops iterate directly over elements, not numeric indexes.
- Use enumerate(items) whenever both index and item are required.
- break terminates the entire loop immediately; continue skips to the next cycle.
- A loop's else block executes only if the loop finished without encountering a break.
- Avoid the range(len(items)) anti-pattern.
Done with this concept?
Mark it complete to track your progress. No login needed.