Loops — for and while
Iterate over data, automate repetitive tasks, and process multiple files with loops
Loops are how you automate repetitive tasks in Python. A data analyst uses loops to process multiple Excel files, iterate over rows for complex logic, or build summary tables. However, in Pandas, you should use vectorised operations instead of loops wherever possible — they are 100x faster. This tutorial teaches both: when to use loops, and when to let Pandas handle iteration internally.
Examples
Key Points
- ✓for loops iterate over any iterable: list, dict, range, DataFrame columns
- ✓enumerate() gives index + value. zip() pairs two lists together
- ✓Never use iterrows() on DataFrames for calculations — use vectorised operations
- ✓Use loops for: file I/O, building lists, complex multi-step row logic
- ✓List comprehensions replace simple for loops with one line
Practice Question
You need to add a "Tax" column to a 100,000-row DataFrame where Tax = Amount × 0.18. Which is the correct approach?
Related Topics
Functions in PythonWrite reusable functions to avoid repeating logic across your analysis scriptsFile Handling in PythonRead and write text files, CSV files, and automate file operations for data pipelinesExcel Automation with PythonAutomate Excel report generation, formatting, and multi-sheet workbooks with openpyxl