Code Pumpkin

for loop | Python Flow Control

October 30, 2018
Posted by Dipen Adroja

Flow control is one of the important aspects of any programming language. In this article, we will learn to iterate over list elements using different variations of for loop in python.

The for loop in Python is used to iterate over iterable objects or a sequence (listtuplestring). Iterating over a sequence is called traversal.

For Loop flow Chart

for loop flow chart

For loop Syntax

for item in iterable:

     Body of for

Here, an item is the variable that takes the value of the item inside the iterable on each iteration. Loop continues until we reach the last item in the sequence. The body of for loop is separated from the rest of the code using indentation.


# variable to store the sum
sum = 0

# iterate over the list
for num in range(10):
	sum = sum + num

# Output: The sum is 45
print("The sum is " + str(sum))


The sum is 45

If you have observed the above code example properly then you should have noticed that we have used one function range. lets have a look at that as well.

The range() function

Range is used to generate a sequence of numbers. The range(10) will generate numbers from 0 to 9. Syntax for range function is:

range(start,stop,step size)

step size defaults to 1.

This function does not store all the values in memory, it would be inefficient. So it remembers the start, stop, step size and generates the next number on the go. That makes this function to be memory efficient.

We can utilize the range function as below to iterate over list of string:

my_list = ['programming', 'codepumpkin', 'avengers']

# iterate over the list using index
for i in range(len(my_list)):
	print("I like " + my_list[i])


I like programming

I like codepumpkin

I like avengers

for loop with else

One variation of for loop to use it with else block. The else part will be executed if there is no more items to be iterable. 

Break statement can be used to break a for loop. In such case, the else part is ignored.

The syntax is as below:

for item in iterable:

     Body of for


    Else code here



for i in numbers:
    print("No items left.")







No items left.

That't it for now. We will see while loop in the next article.


Happy Learning 🙂



About the Author

Dipen Adroja
Coder, Blogger, Wanderer, Philosopher, Curious pumpkin

Tags: ,

Comments and Queries

<pre><code class="java"> 
String foo = "bar";
Total Posts : 124
follow us in feedly
Contribute Your Articles

Cauvery Calling

Cauvery Calling



Like Us On Facebook