Loops in Python
Iterate over data with for and while loops — automate repetitive data tasks
Loops let you repeat an action for every item in a collection. In data work, you use loops to process multiple files, iterate over rows, apply transformations, and automate batch operations.
Python has two loop types: for (iterate over a sequence) and while (repeat until a condition is false). In data analysis, for loops are used far more often.
Examples
Key Points
- ✓for item in collection: — iterates over any iterable (list, dict, range, DataFrame rows)
- ✓enumerate(list) gives both index and value: for i, val in enumerate(list)
- ✓range(start, stop, step) generates a sequence of numbers
- ✓break exits the loop early; continue skips to the next iteration
- ✓Avoid looping over pandas DataFrame rows with for — use vectorised operations instead
Practice Question
What does enumerate(["a", "b", "c"]) produce when iterated?