Loops š¶
What You'll Learn
- ā
How
forloops work and when to use them - ā
How
whileloops work and when to use them - ā
range(),enumerate(),zip()and more - ā Nested loops with real examples
- ā
break,continue,pass, andelseon loops - ā List comprehensions as a loop shortcut
- ā Common mistakes and infinite loop traps
š Introduction¶
A loop lets you repeat a block of code multiple times without writing it over and over. Python has two main loop types ā for for iterating over sequences, and while for repeating based on a condition.
New to Python?
Start with Basics ā Complexity Analysis ā Data Structures ā Algorithms before jumping into practice problems.
Already know Python?
Jump straight to Data Structures or Algorithms depending on what you're revising.
Keep in mind
Every topic includes real code examples, memory diagrams, and practical use cases ā read them carefully, don't just skim the code.
š for Loop¶
1ļøā£ Basic for Loop¶
Iterates over any iterable ā list, string, tuple, dict, set, range.
Real-Life Example
- For each student in the class ā print their name
- For each item in the cart ā calculate total
Output:
Memory Visualization
fruits = ["apple", "banana", "cherry"]
Iteration 1: fruit āāāŗ "apple" ā body runs
Iteration 2: fruit āāāŗ "banana" ā body runs
Iteration 3: fruit āāāŗ "cherry" ā body runs
no more items ā loop ends
2ļøā£ range() Function¶
Generates a sequence of numbers ā perfect for index-based loops.
Memory Visualization
range(1, 6):
āāāāā¬āāāā¬āāāā¬āāāā¬āāāā
ā 1 ā 2 ā 3 ā 4 ā 5 ā
āāāāā“āāāā“āāāā“āāāā“āāāā
range() does NOT store all values in memory ā
it generates them one by one (lazy evaluation) ā
range() is Memory Efficient
range(1000000) does not create a million numbers in memory. It generates each number on demand ā making it very fast and efficient.
3ļøā£ enumerate() ā Index + Value¶
Get both the index and value while looping.
fruits = ["apple", "banana", "cherry"]
# Without enumerate ā
for i in range(len(fruits)):
print(i, fruits[i])
# With enumerate ā
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
# Start from 1
for index, fruit in enumerate(fruits, start=1):
print(f"{index}. {fruit}")
Output:
Always use enumerate() instead of range(len(...))
It's cleaner, more Pythonic, and less error-prone.
4ļøā£ zip() ā Loop Two Lists Together¶
Iterate over multiple iterables in parallel.
names = ["Alice", "Bob", "Charlie"]
scores = [95, 87, 92]
for name, score in zip(names, scores):
print(f"{name}: {score}")
Output:
zip() with unequal lengths
Output:
zip() stops at the shortest iterable
Items 4 and 5 from list a are ignored. Use itertools.zip_longest() if you need all elements.
5ļøā£ Looping Over Different Iterables¶
6ļøā£ Nested for Loops¶
A loop inside another loop.
# Multiplication table
for i in range(1, 4):
for j in range(1, 4):
print(f"{i}Ć{j}={i*j}", end=" ")
print()
Output:
Star Pattern
Output:
Memory Visualization
for i in range(1, 3): ā outer loop
for j in range(1, 3): ā inner loop
i=1: j=1 ā (1,1)
j=2 ā (1,2)
i=2: j=1 ā (2,1)
j=2 ā (2,2)
Total iterations = outer Ć inner = 2 Ć 2 = 4
Nested Loop Complexity
Every extra level of nesting multiplies the number of iterations. Three nested loops over n items = O(n³) ā avoid deep nesting when possible.
š while Loop¶
7ļøā£ Basic while Loop¶
Repeats as long as a condition is True. Use when you don't know how many iterations you need.
Real-Life Example
- While ATM has balance ā allow withdrawals
- While user hasn't guessed correctly ā keep asking
Output:
Memory Visualization
count = 1
Check: count <= 5 ā 1 <= 5 ā True ā print 1, count = 2
Check: count <= 5 ā 2 <= 5 ā True ā print 2, count = 3
Check: count <= 5 ā 3 <= 5 ā True ā print 3, count = 4
Check: count <= 5 ā 4 <= 5 ā True ā print 4, count = 5
Check: count <= 5 ā 5 <= 5 ā True ā print 5, count = 6
Check: count <= 5 ā 6 <= 5 ā False ā loop ends ā
8ļøā£ while True + break¶
An intentional infinite loop that exits on a condition ā common for menus and input validation.
while True:
command = input("Enter command (quit to exit): ")
if command == "quit":
print("Goodbye! š")
break
print(f"Running: {command}")
Output:
Practical: Input Validation
while True:
age = int(input("Enter your age (1-120): "))
if 1 <= age <= 120:
print(f"Valid age: {age} ā
")
break
print("Invalid! Try again ā")
Output:
Enter your age (1-120): -5
Invalid! Try again ā
Enter your age (1-120): 200
Invalid! Try again ā
Enter your age (1-120): 25
Valid age: 25 ā
Infinite Loop Trap
šļø Loop Control¶
9ļøā£ break ā Exit Loop Early¶
Stops the loop immediately and jumps out.
numbers = [1, 3, 7, 2, 9, 4]
for num in numbers:
if num == 2:
print("Found 2! Stopping.")
break
print(num)
Output:
Memory Visualization
for num in [1, 3, 7, 2, 9, 4]:
num=1 ā print 1
num=3 ā print 3
num=7 ā print 7
num=2 ā BREAK āāāāāāāāāāāāāāāāāāāāāāāāāāā
num=9 ā never reached ā
num=4 ā never reached ā¼
continues after loop
š continue ā Skip Current Iteration¶
Skips the rest of the current iteration and moves to the next one.
Output:
Practical: Filter Invalid Data
data = [10, -5, 20, -3, 15, 0, 8]
total = 0
for num in data:
if num <= 0:
continue
total += num
print(f"Sum of positives: {total}")
Output:
1ļøā£1ļøā£ pass ā Do Nothing¶
A placeholder for empty blocks. Python requires at least one statement in a block.
Output:
1ļøā£2ļøā£ else on Loops¶
The else block runs only if the loop finished without hitting break.
numbers = [1, 3, 5, 7, 9]
target = 6
for num in numbers:
if num == target:
print(f"Found {target}!")
break
else:
print(f"{target} not found in list.")
Output:
With break ā else is skipped
numbers = [1, 3, 5, 6, 9]
target = 6
for num in numbers:
if num == target:
print(f"Found {target}!")
break
else:
print(f"{target} not found.")
Output:
Loop else ā Perfect for Search
Avoids the need for a found = False flag variable. Clean and Pythonic.
ā” List Comprehensions¶
A compact, Pythonic way to build lists using a single line instead of a loop.
Basic Comprehension¶
With Condition¶
# Even numbers only
evens = [i for i in range(1, 11) if i % 2 == 0]
print(evens)
# Words longer than 4 chars
words = ["hi", "hello", "Python", "AI", "code"]
long_words = [w for w in words if len(w) > 4]
print(long_words)
Output:
Nested Comprehension¶
# Flatten a 2D list
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [num for row in matrix for num in row]
print(flat)
Output:
Don't Overuse Comprehensions
If your comprehension is hard to read in one line ā use a regular loop. Readability > cleverness.
ā Quick Reference Summary¶
| Loop / Statement | Syntax | Use When |
|---|---|---|
for |
for x in iterable: |
Known sequence to iterate |
while |
while condition: |
Condition-based repetition |
range() |
range(start, stop, step) |
Numeric loops |
enumerate() |
for i, v in enumerate(lst): |
Need index + value |
zip() |
for a, b in zip(x, y): |
Parallel iteration |
break |
break |
Exit loop early |
continue |
continue |
Skip current iteration |
pass |
pass |
Empty block placeholder |
for-else |
for ... else: |
Detect if break was hit |
| List comp | [x for x in lst if cond] |
Build lists concisely |