Python Loops (while & for Loops)

๐Ÿ Python 3.12+ ๐ŸŸข Chapter 8 of 65 ๐Ÿ“‚ Phase 2: Operators & Control Flow ๐Ÿ“… 2026 Edition
๐Ÿ“Œ Covered in this chapter: while Loops ยท for Loops ยท range() Function ยท enumerate() ยท zip()
Master iterative programming in Python: while loops, for loops, range() lazy evaluation, and unpacking with enumerate() and zip().
1The while Loop (Condition-Controlled Repetition)

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:

  1. Initialization: A counter or state variable defined before the loop starts (e.g. count = 1).
  2. Condition Test: Evaluated at the start of every iteration (e.g. while count <= 5:).
  3. 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!
๐Ÿ’ป Example 1: while Loop Counting 1 to 5
# 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! โœ…")
๐Ÿ” Step-by-Step Dry Run (Iteration Table):
Iteration #Condition (count <= 5)Action / PrintedNew count value
Iteration 11 <= 5 (True)Prints Current Count is: 1count = 2
Iteration 22 <= 5 (True)Prints Current Count is: 2count = 3
Iteration 33 <= 5 (True)Prints Current Count is: 3count = 4
Iteration 44 <= 5 (True)Prints Current Count is: 4count = 5
Iteration 55 <= 5 (True)Prints Current Count is: 5count = 6
Iteration 66 <= 5 (False!)Loop terminates!Exit loop
2The for Loop & Iterating Over Sequences

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):

๐Ÿ’ป Example 2: for Loop Iterating over a List
# 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)
๐Ÿ” Line-by-Line Code Breakdown:
  • for lang in languages:: On each loop cycle, Python automatically takes the next item from languages and binds it to the variable lang.
  • No index bounds or manual length checks (len()) needed!
3The range() Built-in Sequence Generator

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 is 0).
  • stop: Ending integer (exclusive โ€” loop stops 1 number before!).
  • step: Stride/increment between each number (default is 1).
๐Ÿ’ป Example 3: range() with Step Increment
# 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()
๐Ÿ” Memory Efficiency Note:

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!

4enumerate() for Index and Value Numbering

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:

๐Ÿ’ป Example 4: Numbered Output with enumerate()
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}")
๐Ÿ” Parameter Breakdown:
  • start=1 sets the initial rank counter to 1 instead of standard zero.
  • In each cycle, rank gets the number and name gets the student's string.
5Parallel Iteration with zip()

The zip() function allows you to iterate over multiple lists simultaneously in parallel, pairing up corresponding elements into tuples:

๐Ÿ’ป Example 5: Parallel Iteration with zip()
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}")
๐Ÿ” Output Breakdown:

In iteration 1: Alice, 95, A+. In iteration 2: Bob, 88, B+. zip() stops cleanly when the shortest list finishes.

โš ๏ธ Common Developer Pitfall: Modifying a List While Iterating Over It

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.

๐Ÿ’ป Hands-on Interactive Practice Challenge

Print a multiplication table for the number 5 from 1 to 10.

Python 3 Practice Challenge โ–ถ Run in Compiler
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}")
Run This Challenge in Online Python IDE โ†’
โ“ Frequently Asked Questions (FAQ)

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].

OC
Written by Our Compiler Technical Editorial Team
Reviewed for accuracy & tested on Python 3.12+ runtime ยท Last updated August 2026