codewithjohn.dev
Published on

Understanding For Loops in Python

In this article, We are going to explore the Python for loop in detail with the help of examples and learn how to iterate over different sequences, including lists, tuples, and more. Also, we'll learn to control the flow of the loop using the break and continue statements.

In the Python programming language, for loops are also called "definite loops." They are useful when you want to execute the same code for each item in a given sequence. Unlike while loops, or indefinite loops, which execute an action until some condition is met,

Basic Syntax of a For Loop in Python

The basic syntax or the formula of for loops in python Is like below.

for item in iterable:
    # Code block to be executed for each item

The item variable takes the value of each element in the iterable object, and the code block following the colon is executed for each iteration.

How to Iterate Over a String with a For Loop

As we mentioned above, we can iterate over any iterable data with a for loop. In Python, strings are also iterable, so we can use the for loop to iterate over strings.

name = 'John Doe'
for char in name:
    print(char)

Lists, Tuples, and sets are iterable objects. So Let's look at how we can loop over the elements within these objects now.

How to Iterate Over a Dictionary with For Loop

In Python Dictionary have both keys and values associated with each entry. so looping in Dictionary is slightly different compared to looping over other iterable objects like lists or strings.

Here's an example of how to loop over a dictionary:

student_grades = {
    "John": 85,
    "Emma": 92,
    "Michael": 78,
    "Sophia": 95
}

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

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

# Looping over both keys and values
for student, grade in student_grades.items():
    print(student, grade)

How to Iterate Over List and Tuples with For Loop

Lists and tuples are both iterable objects in Python. You can iterate over their elements using a for loop. For example:

fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
    print(fruit)

You can loop over Tuples in the same way

Python for loop with range() function

Python range() is one of the built-in functions. The function returns a sequence of numbers, starting from 0 by default, and increments by 1 and stops before a specified number.

The syntax and parameter for the range() function is as follows:

range(start, stop, step)
  • start (Optional). An integer number specifying at which position to start. Default is 0
  • stop (Required). An integer number specifying at which position to stop (not included).
  • step (Optional). An integer number specifying the incrementation. Default is 1

Here's an example of how to loop over a range:

for num in range(1, 5):
    print(num)

Using the Enumerate Function

The enumerate() function can be used to iterate over a sequence and retrieve both the index and value of each element. For example:

fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
    print(index, fruit)

Nested For Loops

When you have multi-dimensional data structures you can nest one or more for loops within another for loop to perform iterations.

Here's an example:

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
    for num in row:
        print(num)

Breaking out of the Loop with Break

You can use The break keyword to exit the for loop prematurely. It's used to break the for loop when a specific condition is met. In the example below, the execution did not get to the numbers 8 and 10 because we used the break keyword to break out of the loop because we didn't need to keep iterating over the remaining elements.

numbers = [2, 4, 6, 8, 10]

for num in numbers:
    if num == 8:
        break
    print(num)

Skipping Iterations with Continue:

Like the break keyword, You can also use the continue keyword to skip the current iteration and continue with the rest.

In the example below, we use the continue keyword so the loop skips 2 and continues the loop after it:

numbers = [2, 4, 6, 8, 10]
for number in numbers:
    if number == 8:
        continue
    print(number)

How to Use the else Keyword in Python with for loop

You can also use the else keyword to specify that a block of code should run after the loop is done. The else block is executed only if the loop completes all iterations without encountering a break statement.

Here's an example to demonstrate the usage of the else keyword with a for loop:

numbers = [2, 4, 6, 8, 10]

for num in numbers:
    if num == 12:
        break
    print(num)
else:
    print("All numbers iterated successfully.")