For Loops in Python

A for loop is a fundamental control structure in Python, used to iterate over a sequence (such as a list, tuple, dictionary, set, or string) and execute a block of code for each item in the sequence. For loops are especially useful when you want to perform an operation on each element of a collection or iterate over a range of numbers.

Basic For Loop

The basic structure of a for loop allows you to traverse through all elements of a sequence and apply the same block of code to each element.

Python
fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(fruit)

# Output:
# apple
# banana
# cherry

In this example, the loop iterates over the fruits list, printing each fruit to the console. The loop automatically stops after the last item is processed.

Using Range Function

The range() function is commonly used in for loops to generate a sequence of numbers. This is particularly useful when you need to iterate a specific number of times or generate a sequence of indices.

Python
for i in range(5):
    print(i)

# Output:
# 0
# 1
# 2
# 3
# 4

In this example, range(5) generates a sequence of numbers from 0 to 4 (5 is not included), and the loop iterates over this sequence, printing each number.

Customizing the Range

You can customize the range() function to start at a different number or change the step value:

Python
for i in range(2, 10, 2):
    print(i)

# Output:
# 2
# 4
# 6
# 8

Here, range(2, 10, 2) starts at 2 and ends before 10, incrementing by 2 on each iteration. This results in the numbers 2, 4, 6, and 8 being printed.

Using Break and Continue

The break and continue statements are control flow tools that can alter the behavior of a loop.

Break Statement

The break statement is used to exit the loop prematurely when a specific condition is met:

Python
for i in range(5):
    if i == 3:
        break
    print(i)

# Output:
# 0
# 1
# 2

In this example, the loop prints numbers from 0 to 2. When i equals 3, the break statement is executed, which stops the loop immediately.

Continue Statement

The continue statement skips the current iteration and moves to the next one:

Python
for i in range(5):
    if i == 3:
        continue
    print(i)

# Output:
# 0
# 1
# 2
# 4

Here, when i equals 3, the continue statement is executed, causing the loop to skip the print statement for that iteration. Thus, 3 is not printed.

Nested For Loops

For loops can be nested within other loops. This is useful when working with multi-dimensional data structures, like lists of lists.

Python
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

for row in matrix:
    for item in row:
        print(item, end=" ")
    print()

# Output:
# 1 2 3
# 4 5 6
# 7 8 9

In this example, the outer loop iterates over each row of the matrix, and the inner loop iterates over each item in the current row, printing it. The end=" " argument in the print() function ensures that the items are printed on the same line, with a space between them.

Looping with Dictionaries

You can also use for loops to iterate over the keys, values, or key-value pairs in a dictionary:

Python
student_grades = {"Alice": 85, "Bob": 92, "Charlie": 78}

# Looping through keys
for student in student_grades:
    print(student)

# Looping through values
for grade in student_grades.values():
    print(grade)

# Looping through key-value pairs
for student, grade in student_grades.items():
    print(f"{student}: {grade}")

# Output:
# Alice
# Bob
# Charlie
# 85
# 92
# 78
# Alice: 85
# Bob: 92
# Charlie: 78

This example demonstrates different ways to iterate over the contents of a dictionary. The .items() method is particularly useful when you need to access both keys and values simultaneously.

Conclusion

For loops are versatile and powerful tools in Python, enabling you to automate repetitive tasks, iterate over collections, and manage complex data structures efficiently. Whether you"re working with simple lists or multi-dimensional arrays, mastering for loops is a fundamental step in becoming proficient with Python.