Python for Loop

In Python, a for loop is used to iterate over a sequence (like a list, tuple, string, dictionary, or range) and execute a block of code for each item it contains.

Syntax

for variable in sequence:
    # code to execute

Breakdown of Parts

for: It is a Python keyword that starts a loop.

variable: It is a temporary placeholder that stores the current item in the sequence during each iteration. You can name it almost anything you want (e.g., item, element, i, x, name, fruit).

in: The in keyword tells Python where to look for items to loop over.

sequence: The sequence is a collection of items you want to loop over (e.g., list, tuple, string, dictionary, or range).

Colon (:) : You must put a colon at the end of the for statement. It tells Python that the indented lines that follow are the code to run for each item in the sequence.

Indented code block: The code indented below the for statement is the body of the loop and will be executed for each item in the sequence.

Looping Through a List

A Python list is an ordered collection of items (elements) that can be looped through, allowing you to access and process each item one at a time.

For example:

fruits = ["apple", "banana", "mango"]

for fruit in fruits:
    print(fruit)

Output:

apple
banana
mango

Here is how the for loop works step-by-step:

(1) First Iteration: The loop retrieves the first item from the fruits list, which is "apple", and assigns it to the variable fruit. Then the code inside the loop executes and prints "apple" to the output.

(2) Second Iteration: The loop retrieves the next item from the fruits list, which is "banana", and assigns it to the variable fruit. Then the code inside the loop executes and prints "banana" to the output.

(3) Third Iteration: The loop retrieves the next item from the fruits list, which is "mango, and assigns it to the variable fruit. Then the code inside the loop executes and prints "mango" to the output.

(4) End of loop: Python sees there are no more items in the fruits list, so the loop terminates.

Looping Through a String

Python strings are a sequence of characters, so you can loop through a string and access each character one by one.

For example:

for char in "mango":
    print(char)

Output:

m
a
n
g
o

Using range() With for Loop

The range() function is used to generate a sequence of numbers and is commonly used to repeat an action a specific number of times.

Here is the syntax of the range() function:

range(start, end, step)

Where,

start (Optional): The starting number of the sequence (default is 0).

end (Required): Number at which to stop (the sequence goes up to, but does not include, this number).

step (Optional): The difference between each number in the sequence (default is 1).

For example:

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

Output:

0
1
2
3
4

In this example, the range() function generates a sequence of numbers for the for loop to iterate over.

Since the start parameter is omitted, it defaults to 0, and because the step parameter is also omitted, it defaults to 1.

Therefore, the statement range(5) starts from 0 and goes up to, but does not include, 5. This means it produces the sequence: 0, 1, 2, 3, 4.

The for loop retrieves each of these numbers one by one and assigns it to the variable i. During each iteration, the statement print(i) executes, displaying the current value of i on the screen.

Using enumerate() With for Loop

If you need to get both the item and its position (index) while looping through a list, you can use the enumerate() function. It gives you the position of each item along with the item itself.

For example:

fruits = ["apple", "banana", "mango"]

for index, fruit in enumerate(fruits):
    print(f"{index}: {fruit}")

Output:

0: apple
1: banana
2: mango

Loop Control Statements

Loop control statements are special statements in Python that alter the normal flow of a loop. They let you alter, skip, or terminate the loop’s execution early.

break Statement

The break immediately stops the loop, even if the condition is still true. You use it to exit a loop once a certain condition is met.

For example:

numbers = [5, 10, 70, 30, 40, 80]

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

Output:

5
10
70
30

In this example, the for loop iterates through each element in the numbers list. When the if condition finds that num is 30, the break statement immediately ends the loop.

continue Statement

The continue statement skips the rest of the code inside the loop for the current iteration and moves to the next iteration. You use it when you want to skip certain values or conditions without breaking the loop entirely.

For example:

numbers = [1, 2, 3, 4, 5]

for num in numbers:
    if num == 3:
        continue
    print(num)

Output:

1
2
4
5

In this example, the for loop iterates through each element in the numbers list. When the if condition finds that num is 3, the continue statement skips the remaining code in that iteration and moves to the next iteration.

pass Statement

The pass statement does nothing and serves as a placeholder when a statement is syntactically required but no action is needed yet. It is commonly used to outline code structure while planning to add the actual logic later.

For example:

for i in range(3):
    pass

The loop executes but performs no action.

Nested for Loops

The nested for loop is a loop inside another loop. The inner loop runs completely every time the outer loop runs once.

For example:

for i in range(2):
    for j in range(5):
        print(f"{i}: {j}")

Output:

0: 0
0: 1
0: 2
0: 3
0: 4
1: 0
1: 1
1: 2
1: 3
1: 4

else in for Loop

The else block after a for loop runs only if the loop completes all its iterations without encountering a break statement.

If the loop is stopped early by a break statement, the else block is skipped.

For example:

for i in range(5):
    print(i)
else:
    print("Loop Completed Without a Break")

Output:

0
1
2
3
4
Loop Completed Without a Break

Let’s see another example with a break statement:

for i in range(5):
    if i == 3:
        break
    print(i)
else:
    print("Loop Completed Without a Break")

Output:

0
1
2