Search This Blog

For Loop

The for Loop in Python

The for loop is one of the most commonly used loops in Python. It allows you to iterate over a sequence (such as a list, tuple, string, or range) and execute a block of code for each item in that sequence. The for loop is very powerful, and its syntax is concise and easy to use.


1. Basic Syntax of the for Loop

The basic syntax of a for loop is as follows:

for item in sequence:
    # Code to execute for each item
  • item: A variable that takes the value of each element in the sequence during each iteration.
  • sequence: The collection or range you want to iterate over (e.g., list, string, tuple, range).
  • The indented code block will be executed once for each element in the sequence.

Example:

# Iterating over a list
fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(fruit)

Output:

apple
banana
cherry

In this example, the for loop iterates over each element in the fruits list, and for each element, it prints the value.


2. Iterating Over a String

You can also iterate over each character in a string using a for loop.

Example:

word = "Python"

for char in word:
    print(char)

Output:

P
y
t
h
o
n

Here, the loop goes through each character in the string "Python" and prints it individually.


3. Using the range() Function

The range() function is often used with a for loop to generate a sequence of numbers. This is particularly useful for repeating an action a specific number of times.

Syntax of range():

range(start, stop, step)
  • start: The starting number of the sequence (optional, default is 0).
  • stop: The sequence will stop before this number.
  • step: The difference between each number (optional, default is 1).

Example 1: Using range() to loop a fixed number of times:

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

Output:

0
1
2
3
4

In this example, the loop iterates 5 times, starting from 0 up to 4 (since stop is exclusive).

Example 2: Using range() with a specific start and step:

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

Output:

2
4
6
8

This loop starts at 2, stops before 10, and steps by 2 each time (i.e., 2, 4, 6, 8).


4. Iterating Over a Dictionary

In Python, dictionaries are collections of key-value pairs. You can iterate over them using a for loop in a few different ways.

Example 1: Iterating over keys:

person = {"name": "Alice", "age": 25, "city": "New York"}

for key in person:
    print(key)

Output:

name
age
city

In this example, the loop iterates over the keys of the dictionary.

Example 2: Iterating over values:

for value in person.values():
    print(value)

Output:

Alice
25
New York

This loop iterates over the values of the dictionary.

Example 3: Iterating over key-value pairs:

for key, value in person.items():
    print(f"{key}: {value}")

Output:

name: Alice
age: 25
city: New York

In this case, the loop iterates over both the keys and values simultaneously.


5. Nested for Loops

A nested for loop is a for loop inside another for loop. This is useful when you need to iterate over multiple dimensions, such as a list of lists or a matrix.

Example:

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

for row in matrix:
    for num in row:
        print(num, end=" ")
    print()  # Print a newline after each row

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 the numbers in each row.


6. The else Clause with Loops

You can also use an else clause with a for loop. The else block will execute if the loop completes without hitting a break statement. If the loop is terminated early using break, the else block will not be executed.

Example:

for i in range(5):
    print(i)
else:
    print("Loop finished.")

Output:

0
1
2
3
4
Loop finished.

Here, the else block is executed after the loop finishes normally.

Example with break:

for i in range(5):
    if i == 3:
        break
    print(i)
else:
    print("Loop finished.")  # This will not be executed

Output:

0
1
2

Since the break statement terminates the loop when i is 3, the else block is skipped.


7. Looping Through Multiple Sequences Using zip()

You can use the zip() function to iterate over multiple sequences in parallel. This is useful when you have two or more collections and want to process them together.

Example:

names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]

for name, age in zip(names, ages):
    print(f"{name} is {age} years old.")

Output:

Alice is 25 years old.
Bob is 30 years old.
Charlie is 35 years old.

In this example, zip() combines the names and ages lists, and the for loop iterates through both sequences at the same time.


Summary

  • The for loop is used to iterate over a sequence (like a list, string, or range) and perform actions for each item.
  • You can use the range() function to generate a sequence of numbers for looping.
  • Iterating over dictionaries can be done with .keys(), .values(), and .items().
  • Nested for loops allow you to iterate over multi-dimensional collections.
  • The else block with loops executes only when the loop is not terminated early by a break.
  • The zip() function helps in iterating through multiple sequences at the same time.

Mastering for loops is essential for effective programming in Python, as they allow for repetitive tasks and processing collections of data with ease.

Popular Posts