Python foreach Loop

The “foreach” loop is used in programming languages like Java, C++, PHP, etc. to iterate over each element of a list, array, etc. In Python, there is no keyword similar to the “foreach” loop but there is a “for” loop keyword that is almost similar to “foreach”. The for loop or foreach loop both iterate over the sequence or collection of objects but the foreach loop iterates over the elements rather than maintaining a counter or iteration.

In this blog, we will demonstrate multiple ways to use the foreach loop in Python. The below contents will be discussed in detail with numerous examples:

How to Create a Python foreach Loop?

To create a for each loop different methods are used in Python. These methods include the “for-in” statement, “list comprehension” and “map()” functions. We will discuss all these methods with appropriate examples:

Method 1: Using for and in Expression

The “for” and “in” expressions are used in the below code to achieve the functionality of for-each loop:

Code:

for i in [5, 10, 15, 20]:
    print(i)

The “for” and “in” expression is used to iterate over the given list and display the value of every element.

Output:

The for-each loop has been executed using the for and in expressions.

Method 2: Using List Comprehension

The following code uses list compression to create a foreach loop:

Code:

list_1 = [55, 45, 65, 75]
new_list = [i+5 for i in list_1]
print(new_list)
  • In the list comprehension, for loop iterate over the given list and perform “i+1” computation for each element of the list.
  • After operating on each element of the list the final list will be returned.

Output:

A new list is created by adding “5” to each element of the list.

Method 3: Using map() Function

The “map()” function can be used as an alternative to the “for each” loop in Python. Here is an example code:

Code:

list_value = [1, 2, 3, 4, 5]

def sum(x):
    return x+5

output = map(sum, list_value)
print(list(output))
  • The list named “list_value” is created in the program.
  • The function named “sum” is defined that will add 5 to every element of the list.
  • The “map()” function is used to get a map object after applying the stated function to each element value of the list. 
  • The “map()” function returns the map object iterator which is passed as an argument to the list to return a new list iterator.

Output:

The map() function successfully applies the “sum” function to the given list element.

Conclusion

The “for-in” expression, “list comprehension” and “map()” function is used to perform the “for each” loop on every element of the given iterator in Python. There is no keyword similar to “for each” in Python. However, some methods perform a similar functionality just like the “for-each” loop. The “map()” function is used to iterate over the sequence and apply a function to each element of the sequence. This guide delivered various ways to perform Python for-each loop.