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

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

Bestseller

Let Us Python – 4th Edition: Python Is Future, Embrace It Fast

This book is for everyone who wish to learn python programming language. It strengthens the foundations, as detailed explanation of programming language concepts are given. Lists down all important points that you need to know related to various topics in an organized manner. Prepares you for coding related interview and theoretical questions. Provides In depth explanation of complex topics and Questions. Focuses on how to think logically to solve a problem. You will learn about Data types, Control flow instructions, console & File Input/output Strings, list & tuples, List comprehension Sets & Dictionaries, Functions & Lambdas Dictionary Comprehension Modules, classes and objects, Inheritance Operator overloading, Exception handling Iterators & Generators, Decorators, and Command-line Parsing