Looping is iterating over a sequence. Python's loops are clean — no manual indices, no off-by-one bugs — because the language pushes you to iterate over items, not positions.
for loops
fruits = ["apple", "mango", "banana"]for fruit in fruits:print(fruit)# Iterate over a string — char by charfor ch in "Albero":print(ch)# Iterate over a dict — keys by defaultuser = {"name": "Aanya", "age": 28}for key in user:print(key, "=", user[key])# Iterate over file lines (one of the most common Python tasks)with open("data.csv") as f:for line in f:print(line.rstrip())
range()
range(stop), range(start, stop), range(start, stop, step). The end is exclusive.
for i in range(5):print(i) # 0, 1, 2, 3, 4for i in range(2, 7):print(i) # 2, 3, 4, 5, 6for i in range(0, 20, 3):print(i) # 0, 3, 6, 9, 12, 15, 18# Countdownfor i in range(10, 0, -1):print(i, end=" ")# 10 9 8 7 6 5 4 3 2 1
enumerate() & zip()
fruits = ["apple", "mango", "banana"]# enumerate gives you (index, item) pairsfor i, fruit in enumerate(fruits):print(f"{i}: {fruit}")# Start the index at a different numberfor i, fruit in enumerate(fruits, start=1):print(f"{i}: {fruit}")# zip pairs up two iterables in lockstepprices = [120, 80, 50]for fruit, price in zip(fruits, prices):print(f"{fruit}: ₹{price}")# zip stops at the shortest iterablefor a, b in zip([1, 2, 3], ['a', 'b']):print(a, b)# 1 a# 2 b
while loops
A while loop runs as long as a condition is true. Use it when you don't know how many iterations you need upfront.
# Read until EOFn = 0while True:line = input()if line == "STOP":breakn += 1print(f"Read {n} lines")# Retry patternattempts = 0while attempts < 3:if try_login():breakattempts += 1else:print("Locked out.")
break, continue, else
break— exit the closest enclosing loop immediately.continue— skip the rest of this iteration and start the next.elseon a loop — runs only if the loop completed without abreak.
# Find the first prime in a rangefor n in range(2, 100):for d in range(2, n):if n % d == 0:break # not primeelse:print(f"{n} is prime")break # found the first one
Nested loops
# Multiplication table 1-5for i in range(1, 6):for j in range(1, 6):print(f"{i*j:>4}", end=" ")print()# Output:# 1 2 3 4 5# 2 4 6 8 10# 3 6 9 12 15# 4 8 12 16 20# 5 10 15 20 25
Iteration patterns
Building a list from a loop → use a comprehension
# Manualsquared = []for n in range(10):squared.append(n * n)# Idiomatic — same speed, more readablesquared = [n * n for n in range(10)]
Pairwise iteration
# Compare consecutive elementsnums = [4, 7, 2, 9, 1]for a, b in zip(nums, nums[1:]):print(a, "→", b, "diff:", b - a)# Or use itertools.pairwise (Python 3.10+)from itertools import pairwisefor a, b in pairwise(nums):print(a, b)
Key takeaways
- 01Iterate over items, not indices — for x in lst, never for i in range(len(lst)).
- 02enumerate() gives you (index, item); zip() pairs two iterables in lockstep.
- 03while is for "until X happens"; for is for "for each item".
- 04else on a loop runs only if it didn't break — useful for "search and report".
- 05Replace "build a list with append" loops with list comprehensions.
