Python

How to Implement a _ForEach_ Loop in Python

A “foreach” or “for-each” loop is a kind of loop that you can use in several programming languages. It iterates over a collection of items to perform a particular task while abstracting away the iteration details throughout the process, buying it with immunity against errors.

Unlike other programming languages, the foreach loop isn’t a built-in feature of Python. However, you can implement a similar functionality using a “for” loop instead. Moreover, you can also use the map() function as a foreach equivalent.

The map() function in Python has the same significance as the foreach loop in other programming languages. Keep reading this guide to briefly understand how to implement a foreach loop in Python.

How to Implement a Foreach Loop in Python

If you want to implement a “foreach” in Python, this section consists of multiple examples to help you understand how to do so. Moreover, the basic syntax is as follows:

for item in iterable :
#Add your code here

This code executes for every element that is present in this iterable.

Implementing the Foreach Loop Using β€œFor” Loop

Let’s look at the example to create a program of the foreach loop using β€œfor” loop. In the following program, we iterate over the integers array to print all the numbers:

integers = [10, 12, 14, 16, 80]
for num in integers :
    print(num)

The result is as follows upon compilation:

Implementing the Foreach Loop Using β€œFor” Loop in Advance Program

If you want to perform an action for every iterated item of the collection, you can use the following program:

numbers =[1, 2, 3, 4, 5]
addition = 0
for num in numbers:
    addition += num
    print("The sum is:", addition)

Here, the value of every number it iterates over is added to the variable named addition.

Upon running the program, you’ll get the following results:

Using the Nested Foreach Loop to Create a Star Pattern

You can also use the nested foreach loop to create the star pattern.

rows = 7
for m in range(1, rows + 1):
    for n in range(1, m + 1):
        print("*", end=" ")
    print('')

The previously written program produces a star pattern that resembles a right-angled triangle.

Map() Function to Implement a Foreach Loop

As mentioned previously, the map() function acts as a substitute for the foreach loop in Python. Its syntax is “map(function, iterable)” which means that you must initially define a function according to the task that you want to perform. For example, your code to square the elements of a given collection looks like the following:

def square_function(x):
    return x**2
new_list = [1, 2, 3, 4, 5, 6, 7, 8]
result = map(square_function, new_list)
print(list(result))

You will get the following results after compiling the program:

Conclusion

Since there is no function like foreach loop in Python, this guide explains the various ways to implement a similar functionality. These methods include using the β€œfor” loop and the map() function.

Despite the similarities, the foreach loop has an upper hand over the β€œfor” loop. It improves the overall efficiency and readability of your program. However, you should use the foreach loop when you want to review every collection of item. Otherwise, using the β€œfor” loop is the best option to operate on a specific part of the collection.

About the author

Prateek Jangid

A passionate Linux user for personal and professional reasons, always exploring what is new in the world of Linux and sharing with my readers.