ITERATIONS

Iterations in Python are used to execute a block of code repeatedly. Python provides several ways to perform iterations, including for loops, while loops, and various built-in functions like map() and filter(). Here's an overview of each:

1. for loop:

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 the sequence.

# Iterate over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

# Iterate over a string
for char in "hello":
    print(char)

# Iterate over a range of numbers
for i in range(5):
    print(i)

2. while loop:

The while loop is used to repeatedly execute a block of code as long as a specified condition is true.

# Using a while loop to count from 0 to 4
count = 0
while count < 5:
    print(count)
    count += 1

3. enumerate() function:

The enumerate() function is used to iterate over a sequence while keeping track of the index of each item.

fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
    print(f"Index {index}: {fruit}")

4. zip() function:

The zip() function is used to iterate over multiple sequences simultaneously, pairing corresponding items together.

names = ["Alice", "Bob", "Charlie"]
scores = [85, 90, 75]
for name, score in zip(names, scores):
    print(f"{name}: {score}")

5. map() function:

The map() function applies a given function to each item of an iterable (like a list) and returns an iterator.

numbers = [1, 2, 3, 4, 5]
squared = map(lambda x: x ** 2, numbers)
print(list(squared))  # Output: [1, 4, 9, 16, 25]

6. filter() function:

The filter() function constructs an iterator from elements of an iterable for which a function returns True.

numbers = [1, 2, 3, 4, 5]
even_numbers = filter(lambda x: x % 2 == 0, numbers)
print(list(even_numbers))  # Output: [2, 4]

These are some of the common methods for performing iterations in Python. Depending on the situation, you can choose the most appropriate method for your needs.