6-1. The for loop

1.1 Overview

A for loop is used to iterate over a sequence (like a list, tuple, dictionary, set, or string) and execute a block of code for each item in the sequence. This is akin to using an iterator in other object-oriented languages.

When you use a for loop in Python, it steps through each item in the sequence one by one. The syntax is straightforward:

# Syntax of a for loop
for item in sequence:
    # Do something with item

Here's a practical example:

# Example: Print each item in a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

In this example, the loop goes through each item in the fruits list and prints it out.

How It Differs from Other Languages

In many other languages, the for loop is often used with a counter, like this:

// Example in Java
for (int i = 0; i < fruits.length; i++) {
System.out.println(fruits[i]);
}

In Python, the for loop abstracts away the counter and directly iterates over the items, making the code cleaner and more readable.

Why Use for Loops?

  • Efficiency: You can process each item in a sequence without manually managing a counter.
  • Readability: Code is simpler and easier to understand.
  • Versatility: Works with any iterable, including lists, tuples, sets, dictionaries, and strings.

For Loops in Python Without Indexing Variables

In many programming languages, you might need to initialize an index variable to loop through elements. However, Python’s for loop abstracts this, making iteration over sequences more straightforward and readable.

Looping Through a String

Strings in Python are iterable objects, meaning you can loop through each character in the string using a for loop.

Example: Loop Through the Letters in the Word "Hello"

# Loop through each character in the string "Hello"
for x in "Hello":
    print(x)

Explanation:

  • Iterable String: The string "Hello" is an iterable object, meaning it can be traversed one character at a time.
  • For Loop: The for loop iterates over each character in the string.
  • Print Statement: Inside the loop, the print(x) statement outputs each character individually.
  • Practical Use Cases:
    • Processing Characters: Useful for tasks like character counting, finding vowels/consonants, or any character-specific processing.
    • String Manipulation: Can be used to create new strings based on certain conditions.

 

1.2 The break Statement

The break statement allows you to exit the loop immediately when a specified condition is met, regardless of where you are in the loop.

Example: Exiting the Loop When x is "blue"

Let's look at an example where we have a list of colors. We want to print each color, but stop the loop as soon as we encounter "blue".

colors = ["red", "blue", "green"]
for x in colors:
    print(x)
    if x == "blue":
        break

Explanation:

  • List of Colors: We have a list colors containing "red", "blue", and "green".
  • For Loop: The loop iterates over each item in the list.
  • Print Statement: Each color is printed.
  • Condition: When the loop encounters "blue", the if condition if x == "blue": becomes true.
  • Break Statement: The break statement is executed, which exits the loop immediately.

 

1.3 The continue Statement

The continue statement allows you to skip the rest of the code inside the current iteration of the loop and move to the next iteration.

Example: Skipping "blue"

Let's look at an example where we have a list of colors, and we want to print each color except for "blue".

colors = ["red", "blue", "green"]
for x in colors:
    print(x)
    if x == "blue":
        continue

Explanation:

  • List of Colors: We have a list colors containing "red", "blue", and "green".
  • For Loop: The loop iterates over each item in the list.
  • Condition: When the loop encounters " blue ", the if condition if x == " blue ": becomes true.
  • Continue Statement: The continue statement is executed, which skips the rest of the code in the current iteration and proceeds with the next iteration.
  • Print Statement: The fruit is printed only if it is not " blue ".

 

1.4 The range() Function

The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number. You can also specify a different starting point and increment.

Example: Using the range() Function

Let's look at an example where we use the range() function to loop through a set of code six times.

for x in range(5):
    print(x)

 

Explanation:

  • Range Function: range(5) generates a sequence of numbers from 0 to 4. It does not include 5.
  • For Loop: The loop iterates over each number in the range.
  • Print Statement: Each number in the sequence is printed.

 

Customizing the range() Function

You can customize the range() function by specifying the start, stop, and step values.

Example: Custom Start, Stop, and Step

# Start at 2, stop before 10, increment by 2
for x in range(2, 10, 2):
    print(x)

Explanation:

  • Start Value: The sequence starts at 2.
  • Stop Value: The sequence stops before 10.
  • Step Value: The sequence increments by 2.

 

1.5 The else in for Loop

The else keyword in a for loop provides a way to execute a block of code once the loop has finished iterating over all items. This else block will not execute if the loop is terminated by a break statement.

Example:

Let's look at an example where we print all numbers from 0 to 4 and then print a message when the loop has ended.

for x in range(5):
    print(x)
else:
    print("Finished!")

Explanation:

  • Range Function: range(5) generates a sequence of numbers from 0 to 4.
  • For Loop: The loop iterates over each number in the range.
  • Print Statement: Each number is printed.
  • Else Block: After the loop completes all iterations, the else block is executed, printing "Finished!".

 

1.6 Nested Loops

Nested loops involve having one loop inside another. The inner loop will execute all its iterations for each iteration of the outer loop.

Example:

Let's look at an example where we have a list of colors and a list of sizes. We want to print each color with every size.

colors = ["red", "blue", "green"]
sizes = ["small", "medium", "large"]

for color in colors:
for size in sizes:
    print(color, size)

Explanation:

  • Outer Loop: Iterates over each color in the colors list.
  • Inner Loop: For each color, iterates over each size in the sizes list.
  • Print Statement: Prints the current color and size.