Python For Loops

In Python, the for loop 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 that sequence. It’s one of the most commonly used loops in Python, and it can be used for both iterating over iterable objects and generating sequences of numbers.

1. Basic Syntax of a For Loop

The general syntax for a for loop is:

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

2. Iterating Over a List

You can use a for loop to iterate over each element in a list.

Example:

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

Output:

apple
banana
cherry

Here, the for loop iterates through each item in the fruits list and prints it.

3. Iterating Over a String

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

Example:

word = "hello"
for char in word:
    print(char)

Output:

h
e
l
l
o

This example loops through each character of the string "hello" and prints it.

4. Using range() in For Loops

The range() function is often used in for loops to generate a sequence of numbers. It can be used with one, two, or three arguments:

  • range(stop) — Generates numbers from 0 to stop-1.
  • range(start, stop) — Generates numbers from start to stop-1.
  • range(start, stop, step) — Generates numbers from start to stop-1 with a step size of step.

Example:

# Looping from 0 to 4 (range(stop))
for i in range(5):
    print(i)

Output:

0
1
2
3
4

Example with a specified start and stop:

# Looping from 2 to 5 (range(start, stop))
for i in range(2, 6):
    print(i)

Output:

2
3
4
5

Example with a step:

# Looping from 0 to 10 with a step of 2 (range(start, stop, step))
for i in range(0, 10, 2):
    print(i)

Output:

0
2
4
6
8

5. Iterating Over a Dictionary

You can iterate over a dictionary using a for loop. By default, it iterates over the dictionary’s keys, but you can also access the values or key-value pairs.

Example (iterating over keys):

person = {"name": "John", "age": 30, "city": "New York"}
for key in person:
    print(key)

Output:

name
age
city

Example (iterating over values):

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

Output:

John
30
New York

Example (iterating over key-value pairs):

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

Output:

name : John
age : 30
city : New York

6. Nested For Loops

You can use for loops inside other for loops, which are called nested loops. This is useful when working with multi-dimensional data structures like lists of lists or matrices.

Example:

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

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

Output:

1 2 3 
4 5 6 
7 8 9 

7. Using else with For Loops

Just like with while loops, you can use an else clause with a for loop. The else block will execute after the loop completes normally (i.e., without encountering a break statement).

Example:

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

Output:

0
1
2
3
4
Loop finished successfully!

If the loop is interrupted by a break statement, the else block will not be executed.

Example with break:

for i in range(5):
    if i == 3:
        break  # Exit the loop when i is 3
    print(i)
else:
    print("This will not be printed due to break.")

Output:

0
1
2

8. For Loop with List Comprehension

Python allows you to use for loops in a concise way with list comprehensions. A list comprehension is a compact way to process all or part of the elements in a collection and return a new list.

Example:

# List comprehension to square each number in the range 5
squares = [x**2 for x in range(5)]
print(squares)

Output:

[0, 1, 4, 9, 16]

Summary of for Loops:

  • Iterate over a sequence: The for loop is used to iterate over any iterable object like lists, tuples, dictionaries, or strings.
  • range() function: Often used to generate numbers in a specific range.
  • Accessing dictionary keys and values: You can iterate over the keys, values, or key-value pairs in a dictionary.
  • Nested loops: You can use loops inside other loops to iterate over complex data structures like lists of lists.
  • Using else: The else block runs after the loop completes normally (without break).
  • List comprehensions: A concise way to generate lists using a for loop.
Leave a Reply 0

Your email address will not be published. Required fields are marked *