Skip to main content
Albero Academy

Python Loops

Master for loops, while loops, range(), enumerate(), zip(), break, continue, nested loops, and efficient iteration patterns.

Chapter 9Python16 min readBeginner friendly
  • #Python
  • #Loops
  • #For

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

Python
fruits = ["apple", "mango", "banana"]
for fruit in fruits:
print(fruit)
# Iterate over a string — char by char
for ch in "Albero":
print(ch)
# Iterate over a dict — keys by default
user = {"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.

Python
for i in range(5):
print(i) # 0, 1, 2, 3, 4
for i in range(2, 7):
print(i) # 2, 3, 4, 5, 6
for i in range(0, 20, 3):
print(i) # 0, 3, 6, 9, 12, 15, 18
# Countdown
for i in range(10, 0, -1):
print(i, end=" ")
# 10 9 8 7 6 5 4 3 2 1

enumerate() & zip()

Python
fruits = ["apple", "mango", "banana"]
# enumerate gives you (index, item) pairs
for i, fruit in enumerate(fruits):
print(f"{i}: {fruit}")
# Start the index at a different number
for i, fruit in enumerate(fruits, start=1):
print(f"{i}: {fruit}")
# zip pairs up two iterables in lockstep
prices = [120, 80, 50]
for fruit, price in zip(fruits, prices):
print(f"{fruit}: ₹{price}")
# zip stops at the shortest iterable
for 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.

Python
# Read until EOF
n = 0
while True:
line = input()
if line == "STOP":
break
n += 1
print(f"Read {n} lines")
# Retry pattern
attempts = 0
while attempts < 3:
if try_login():
break
attempts += 1
else:
print("Locked out.")

break, continue, else

  • break — exit the closest enclosing loop immediately.
  • continue — skip the rest of this iteration and start the next.
  • else on a loop — runs only if the loop completed without a break.
Python
# Find the first prime in a range
for n in range(2, 100):
for d in range(2, n):
if n % d == 0:
break # not prime
else:
print(f"{n} is prime")
break # found the first one

Nested loops

Python
# Multiplication table 1-5
for 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

Python
# Manual
squared = []
for n in range(10):
squared.append(n * n)
# Idiomatic — same speed, more readable
squared = [n * n for n in range(10)]

Pairwise iteration

Python
# Compare consecutive elements
nums = [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 pairwise
for a, b in pairwise(nums):
print(a, b)

Key takeaways

  1. 01Iterate over items, not indices — for x in lst, never for i in range(len(lst)).
  2. 02enumerate() gives you (index, item); zip() pairs two iterables in lockstep.
  3. 03while is for "until X happens"; for is for "for each item".
  4. 04else on a loop runs only if it didn't break — useful for "search and report".
  5. 05Replace "build a list with append" loops with list comprehensions.