Python - For Loop

01-Feb-2024

Explore the power of for loops in Python. Learn how to iterate through sequences, perform repetitive tasks efficiently, and leverage the versatility of this fundamental loop structure.

Introduction

Python's for loop is an effective tool that lets you iterate over a list of elements. This guide offers explanations of the syntax and application of the for loop in addition to useful examples that highlight its adaptability.


Example :

# Iterating over elements in a list
fruits = ['mango', 'orange', 'grape']
# Loop through each fruit in the list
for fruit in fruits:
# Print each fruit
print(fruit)



Range Function

The range() function is often used with `for` loops to generate a sequence of numbers.


Example :


# Example: Using range in a for loop
for number in range(1, 5): # Print each number
print(number)

Nested Loops

You can nest `for` loops to iterate over multiple sequences.


Example:

# Example: Nested loop
for i in range(3):
# Outer loop
for j in range(2):
# Inner loop
print(f'Outer loop: {i}, Inner loop: {j}')


Else Clause

When a `for` loop reaches the end of its iterable or the loop condition changes to `False`, the `else` clause is triggered. If a `break` statement ends the loop, it is not carried out.


Example :


# Example: For loop with else clause
for i in range(5):
# Loop body print(i)
else: # Executed when the loop completes without a 'break'
print('Loop completed without break')



Notes

- The `for` loop is a flexible loop that may iterate over a variety of data structures, including strings, tuples, lists, and more.
- `range()` is a frequently used function for creating numerical sequences for iteration.
- You can iterate over several dimensions or sequences using nested loops.


Conclusion


Mastering the `for` loop is essential for efficient and concise iteration in Python. Whether working with simple sequences or dealing with nested structures, the `for` loop provides a flexible and powerful tool for handling repetitive tasks in your code.


Comments