TutorialsPythonLoops in Python

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

for loops — the workhorse of data automation
# Loop over a list
regions = ["Delhi", "Noida", "Gurgaon"]
for region in regions:
    print(f"Processing: {region}")

# Loop with index — use enumerate()
for i, region in enumerate(regions):
    print(f"{i+1}. {region}")
# 1. Delhi
# 2. Noida
# 3. Gurgaon

# Loop over a range
for i in range(5):
    print(i)  # 0 1 2 3 4

for i in range(1, 6):
    print(i)  # 1 2 3 4 5

# Loop over dictionary
stats = {"Total": 1000, "Passed": 850, "Failed": 150}
for key, value in stats.items():
    print(f"{key}: {value}")
Real data work: loop to load multiple CSV files
import pandas as pd
import os

# Load all CSV files in a folder and combine
folder = "monthly_data/"
all_dfs = []

for filename in os.listdir(folder):
    if filename.endswith(".csv"):
        filepath = os.path.join(folder, filename)
        df = pd.read_csv(filepath)
        df["source_file"] = filename  # track origin
        all_dfs.append(df)

combined = pd.concat(all_dfs, ignore_index=True)
print(f"Total rows: {len(combined)}")

# This replaces manually copy-pasting 12 monthly files in Excel
💡 This pattern — loop over files, load each, concat — is one of the most common Python tasks for data analysts at companies.

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?