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.

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

for i in range(1,11):

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]

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\ ================

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

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:

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

================ RESTART: C:/Python_projects/ ================

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

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\ =============

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

Please support us by disabling your adblocker or whitelist this site from your adblocker. Thanks!

turn of adblocker imag