Python Wizard!

Iteration

🔍 Quick Lesson

Iteration in Python refers to the process of repeatedly executing a block of code until a certain condition is met. It allows you to automate repetitive tasks and make your programs more efficient. There are several types of iteration in Python:


1. The `for` Loop

The for loop is the most commonly used iteration structure in Python. It allows you to iterate over sequences such as lists, tuples, strings, or ranges.


                    # Example of a for loop that iterates over a range of numbers
                    for i in range(5):
                        print(i)
                

This loop will print the numbers from 0 to 4. The range(5) generates numbers from 0 up to (but not including) 5.


2. The `while` Loop

The while loop continues to execute a block of code as long as the specified condition is True.


                    # Example of a while loop that prints numbers until a condition is met
                    i = 0
                    while i < 5:
                        print(i)
                        i += 1
                

This loop will also print the numbers from 0 to 4. However, it will keep executing until the condition i < 5 is no longer true.


3. Iterating Over a List

Lists are commonly used with the for loop. You can iterate over a list of items directly:


                    # Example of iterating over a list of names
                    names = ["Alice", "Bob", "Charlie"]
                    for name in names:
                        print(name)
                

This will output each name in the list one by one.


4. Break and Continue Statements

Within a loop, you can use break and continue to control the flow:


                    # Example of using break and continue
                    for i in range(5):
                        if i == 3:
                            break  # Exit the loop when i equals 3
                        elif i == 2:
                            continue  # Skip the rest of the code for i equals 2
                        print(i)
                

This will print 0, 1, and 2 and then stop.


5. Nested Loops

You can also have loops inside other loops, known as nested loops. These are useful when you need to iterate over a multi-dimensional structure like a list of lists.


                    # Example of a nested for loop
                        for i in range(3):
                            for j in range(3):
                                print(f"i={i}, j={j}")
                

This will print all combinations of i and j from 0 to 2.


6. Iteration with Dictionaries

You can also iterate over dictionaries in Python using the items() method, which returns both the key and the value:


                    # Example of iterating over a dictionary
                    person = {"name": "Alice", "age": 25, "city": "New York"}
                    for key, value in person.items():
                        print(key, value)
                

This will print each key-value pair in the dictionary.


7. List Comprehensions

List comprehensions offer a concise way to create lists while iterating. This is a one-liner replacement for most for loops used to create lists.


                    # Example of a list comprehension
                    squared_numbers = [x**2 for x in range(5)]
                    print(squared_numbers)  # Output: [0, 1, 4, 9, 16]
                

This creates a list of the squares of numbers from 0 to 4.


🧠 Mini Quiz: Test Your Knowledge on Iteration

1. Which loop is used to iterate over a sequence in Python?



2. What does the continue statement do in a loop?



3. What will be the output of the following code?


numbers = [1, 2, 3]
for num in numbers:
    print(num)