Python For-Each Loop

In python programming language, thepython for-each loop is another variation of for loop structure. In this loop structure, you get values from a list, set and assign it to a variable during each iteration.

Advertisements

It is little hard to understand without an example. Consider the usual way to using for loop.

for i in range(1,11):
     print(i)

The above construct is useful and variable i can be used as an index to a set or list and solve a problem.

Consider the following example.

my_list = [23, 66, 68, 88, 19]
sum = 0
# now we will use i as an index for the list items
for i in range(0,5):
    sum = sum + my_list[i]
print(sum/5)

In the program above, the sum is 0. The variable i used as index to my_list and adds each item to sum during an iteration.

================ RESTART: C:\Python_projects\For-Each_Loop.py ================
52.8
>>> 

The final value is sum of all number which is divided by 5 to get the average.

Advertisements

For-Each Loop

The for-each loop can be written as follows.

my_list = [55,66,77,88,99]
for list_item in my_list:
    print(list_item)

The value of list is assigned to list_item during the iteration and it printed in the next line.

================ RESTART: C:/Python_projects/For-Each_Loop.py ================
55
66
77
88
99
>>> 

The for-each loop gives an opportunity to go through each item without skipping an member. The range of the loop depends on the set or the list.

A for-each loop can do everything that a traditional for loop can do. Consider the example, where we have modified the average finding program using for loop.

my_list = [55, 66, 77, 88, 99]
sum = 0
# take a sum of the numbers in the list
for list_item in my_list:
   sum = sum + list_item
print(sum/5)

The program does everything that a traditional loop would do and take an average. The range() function is replaced with the my_list.

============= RESTART: C:\Python_projects\For-each_average_2.py =============
77.0
>>> 

Note that the loop will run until it has finished adding each item to the sum.

Advertisements

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.