Python for Loop


In Python, the for loop is a versatile and powerful tool for iterating over sequences like lists, strings, and ranges. It allows you to repeat a block of code a certain number of times or process each item in a collection. Whether you’re a beginner or an experienced developer, mastering the for loop will make your coding much more efficient.

In this blog post, we will explore how the for loop works in Python, different ways to use it, and practical examples to help you get started.


What is a for Loop in Python?

A for loop in Python is used to iterate over a sequence (such as a list, tuple, string, or range) and execute a block of code for each item in the sequence. Unlike other programming languages, Python’s for loop is not just a counter-based loop; it directly works with the elements of a collection.

Basic Syntax of a for Loop:

for item in sequence:
    # Code to execute for each item
  • item is the variable that takes the value of the current element in the sequence.
  • sequence is the collection (list, string, range, etc.) you want to loop over.

Using for Loop with Lists

Lists are one of the most common sequences used with for loops. When you iterate over a list, the loop executes the block of code for each item in the list.

Example 1: Looping Through a List

# Example: Iterating through a list
fruits = ['apple', 'banana', 'cherry', 'date']

for fruit in fruits:
    print(fruit)

Output:

apple
banana
cherry
date

In this example:

  • The loop iterates over each element in the fruits list and prints it.

Using for Loop with Strings

Strings are also iterable, meaning you can loop over each character in a string.

Example 2: Looping Through a String

# Example: Iterating through a string
word = "Python"

for char in word:
    print(char)

Output:

P
y
t
h
o
n

Here:

  • The for loop iterates over each character in the string "Python" and prints each character on a new line.

Using for Loop with range()

The range() function generates a sequence of numbers, which can be used to control the number of iterations in a loop. It’s often used when you want to repeat a block of code a certain number of times.

Example 3: Looping with range()

# Example: Using range() with for loop
for i in range(5):
    print(i)

Output:

0
1
2
3
4

Here:

  • The range(5) function generates a sequence of numbers from 0 to 4.
  • The loop iterates over this sequence and prints each number.

You can also specify a starting point and step size in range(). For example, range(2, 10, 2) generates the numbers 2, 4, 6, 8.

Example 4: Using range() with Custom Start and Step

# Example: Using range() with custom start and step
for i in range(2, 11, 2):
    print(i)

Output:

2
4
6
8
10

Nested for Loops

A nested for loop is a loop inside another loop. It is useful when you want to iterate over multi-dimensional data structures like lists of lists (e.g., matrices).

Example 5: Nested for Loop

# Example: Nested for loop
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

for row in matrix:
    for col in row:
        print(col, end=" ")
    print()  # Adds a new line after each row

Output:

1 2 3
4 5 6
7 8 9

In this example:

  • The outer for loop iterates over the rows of the matrix (list of lists).
  • The inner for loop iterates over each element (column) in a row.

for Loop with else

Python allows you to use an else block with a for loop. The else block is executed when the loop completes normally (i.e., it doesn’t encounter a break statement).

Example 6: Using else with a for Loop

# Example: Using else with for loop
for i in range(3):
    print(i)
else:
    print("Loop completed without a break.")

Output:

0
1
2
Loop completed without a break.

In this case:

  • The else block runs after the loop has iterated over all elements.
  • If the loop is interrupted by a break statement, the else block will not execute.

Using break and continue with for Loops

You can use the break and continue statements to control the flow of a for loop.

  • break: Terminates the loop early when a condition is met.
  • continue: Skips the current iteration and moves to the next iteration.

Example 7: Using break to Exit the Loop

# Example: Using break in a for loop
for i in range(10):
    if i == 5:
        break
    print(i)

Output:

0
1
2
3
4

In this example:

  • The for loop stops when i reaches 5, due to the break statement.

Example 8: Using continue to Skip Iterations

# Example: Using continue in a for loop
for i in range(10):
    if i % 2 == 0:
        continue  # Skip even numbers
    print(i)

Output:

1
3
5
7
9

Here:

  • The continue statement skips the even numbers and prints only the odd numbers.