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:
#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:
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:
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.
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:
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.