Python Loops (while & for Loops)
A while loop repeatedly executes an indented block of code as long as its specified condition remains True.
A properly structured while loop requires three essential components:
- Initialization: A counter or state variable defined before the loop starts (e.g.
count = 1). - Condition Test: Evaluated at the start of every iteration (e.g.
while count <= 5:). - State Update: Incrementing or decrementing the state inside the loop (e.g.
count += 1) to ensure the condition eventually evaluates to False, preventing dangerous infinite loops!
# Step 1: Initialize counter variable
count = 1
# Step 2: Loop condition (Runs as long as count is <= 5)
while count <= 5:
print("Current Count is:", count)
# Step 3: Increment counter by 1 in each cycle
count += 1
# Step 4: Executes after the loop finishes
print("While loop successfully finished! โ
")
| Iteration # | Condition (count <= 5) | Action / Printed | New count value |
|---|---|---|---|
| Iteration 1 | 1 <= 5 (True) | Prints Current Count is: 1 | count = 2 |
| Iteration 2 | 2 <= 5 (True) | Prints Current Count is: 2 | count = 3 |
| Iteration 3 | 3 <= 5 (True) | Prints Current Count is: 3 | count = 4 |
| Iteration 4 | 4 <= 5 (True) | Prints Current Count is: 4 | count = 5 |
| Iteration 5 | 5 <= 5 (True) | Prints Current Count is: 5 | count = 6 |
| Iteration 6 | 6 <= 5 (False!) | Loop terminates! | Exit loop |
In Python, the for loop is an iterator-based loop (similar to "for-each" in Java/C#). Instead of manually managing counters and index boundaries, Python automatically retrieves items from any iterable sequence (lists, strings, tuples, dictionaries):
# Define a list of programming languages:
languages = ["Python", "JavaScript", "Java", "C++"]
# Iterate directly through each element in the list:
for lang in languages:
print("Programming Language:", lang)
for lang in languages:: On each loop cycle, Python automatically takes the next item fromlanguagesand binds it to the variablelang.- No index bounds or manual length checks (
len()) needed!
The built-in range() function produces an arithmetic sequence of numbers on demand. It accepts three parameters: range(start, stop, step):
start: Starting integer (inclusive, default is0).stop: Ending integer (exclusive โ loop stops 1 number before!).step: Stride/increment between each number (default is1).
# 1. Counting 1 to 5 (stops before 6):
print("Counting 1 to 5:")
for i in range(1, 6):
print(i, end=" ")
print()
# 2. Even numbers from 2 to 10 using step=2:
print("\nEven numbers from 2 to 10 (step=2):")
for num in range(2, 11, 2):
print(num, end=" ")
print()
In Python 3, range(1_000_000) uses constant $O(1)$ memory. It calculates each number on the fly as the loop progresses rather than allocating 1 million numbers in RAM!
When looping through a collection, you often need both the index number and the item value. Instead of maintaining a separate counter variable, use the built-in enumerate() function:
students = ["Alex", "Balaji", "Chloe", "David"]
# enumerate() yields both (index, item) in each iteration:
for rank, name in enumerate(students, start=1):
print(f"Rank #{rank}: {name}")
start=1sets the initial rank counter to1instead of standard zero.- In each cycle,
rankgets the number andnamegets the student's string.
The zip() function allows you to iterate over multiple lists simultaneously in parallel, pairing up corresponding elements into tuples:
names = ["Alice", "Bob", "Charlie"]
scores = [95, 88, 92]
grades = ["A+", "B+", "A"]
# Loop over all 3 lists simultaneously:
for name, score, grade in zip(names, scores, grades):
print(f"Student: {name:7} | Score: {score}/100 | Grade: {grade}")
In iteration 1: Alice, 95, A+. In iteration 2: Bob, 88, B+. zip() stops cleanly when the shortest list finishes.
Never remove or append items to a list while looping over it (for item in my_list:). Doing so causes index shifting and skips elements! Instead, iterate over a shallow copy: for item in my_list.copy(): or use a list comprehension.
Print a multiplication table for the number 5 from 1 to 10.
table_num = 5
print(f"โ๏ธ Multiplication Table of {table_num}:")
for i in range(1, 11):
print(f"{table_num} x {i} = {table_num * i}")
Q Does range() allocate all numbers in memory at once in Python 3?
No. In Python 3, range() is a generator-like lazy sequence object that calculates each number on demand, using constant O(1) memory space.
Q What happens when zip() is passed lists of different lengths?
By default, zip() stops as soon as the shortest iterable is exhausted. If you want to continue until the longest iterable finishes, use itertools.zip_longest() with a fillvalue.
Q How do I iterate over a list in reverse order?
You can use reversed(my_list) (which returns a reverse iterator without modifying the list) or slice notation my_list[::-1].