Signup/Sign In

Loops in Python

In this section, we will see how loops work in python. Looping is simply a functionality that is commonly used in programming for achieving repetitive tasks. It can vary from iterating each element of an array or strings, to modifying a whole database.

The thumb rule for using loops is:

If you're writing a similar piece of code, again and again, it's time to go for the loops.

Instead of doing,

>>> a = 1
>>> b = 2
>>> c = 3
>>> d = 4

and so on, do it like,

>>> a = []
>>> {run a loop in this line to store 1, 2, 3, 4 in list a}

In the second code snippet, we will be using a loop, where we will only have to write whatever tedious task we have to achieve, only once, and then put it on a loop. With this, we will be able to achieve an iterative flow for execution.

In python, there are two ways to achieve iterative flow:

  1. Using the for loop
  2. Using the while loop

The for loop

Let us first see what's the syntax,

	[statement to execute]
	[statement to execute when loop is over]
	[else statement is completely optional]

for loop is frequently used to iterate elements of lists. Considering the above syntax, let's say there is a list myList:

>>> myList = [8, 9, 2, 3, 4, 6]

If we want to iterate all the elements of the list myList using the for loop:

for i in myList:
	print (i)

As we can see we are using a variable i, which represents every single element stored in the list, one by one. Our loop will run as many times, as there are elements in the lists. For example, in myList there are 6 elements, thus the above loop will run 6 times.

During the first iteration, the value of i will be 8, while in next it will be 9 and so on, uptill 6, in the last iteration. Doing so, one can easily use these individual list element values inside the loop, as in our case, we have printed them.

Besides this, there is another way of doing it. If you can recall, our old traditional way of accessing an element of the list by index - myList[i]. Although, in this case, we will be using another function range() (or alternatively xrange() can also be used). range() function has already been mentioned in the previous sections too. If you can remember range() function can return you a list of numbers according to the arguments that you provide. For example:

>>> range(5)

[0, 1, 2, 3, 4]


>>> range(5, 10)

[5, 6, 7, 8, 9]


>>> range(2, 12, 2)

[2, 4, 6, 8, 10]

We can use range() function along with the for loop to iterate index number from 0 to len(myList). It will be pretty much like:

for i in range(0, len(myList)):
	print (myList[i])

As you might have noticed, in this case, we will be iterating over a temporary list which contains the index numbers of the actual list. This temporary list is generated using range() function.

The else block in for loop

The else block with the for loop, is executed, once all the elements of the list are iterated or there are no more elements left to iterate in the list. It'll be safe to say that else statement is executed at the end of the loop. Although, as already mentioned in the syntax, it's completely optional to use and in fact, it's not even frequently used.

Looking at some more complex examples, let's say there is a list of lists:

>>> bigList = [[1, 3, 6], [8, 2,], [0, 4, 7, 10], [1, 5, 2], [6]]

How do you think, we will be accessing each element of the list?

The answer is, using a loop within another loop. Since there are lists within a list, thus the outer loop will help in accessing each list of the bigList, and inside that loop, for every list element we will be using another loop.

for i in bigList:
	for j in i:
		print ("Element of list within a list - ", j)

Element of list within a list - 1 Element of list within a list - 3 Element of list within a list - 6 Element of list within a list - 8 Element of list within a list - 2 Element of list within a list - 0 Element of list within a list - 4 Element of list within a list - 7 Element of list within a list - 10 Element of list within a list - 1 Element of list within a list - 5 Element of list within a list - 2 Element of list within a list - 6

The while loop

It's time to learn about the while loop.


while [condition]:
	[statement to execute]
	[statement to execute if condition is false]
	[else statement is completely optional]

Again, in the while loop too, there is an else block, although it's optional and rarely used.

In the first statement, while loop sets a condition, then a statement, and the compiler following the flow of execution, first checks the condition provided in the condition block, if the condition holds True, then the statement is executed.

Once the statement is executed, the compiler checks the condition again, if it's True again then the statement is again executed, otherwise the else block is executed (if provided) or simply the flow control breaks out of the while loop (if else statement is not mentioned).

Here is an example:

Caution: Don't try this example in IDE or IDLE or anywhere.

while True:
	print ("I am printing because the condition is True")

Since here we have set our condition to be True, hence the compiler will execute the statement the first time. In next iteration, the condition will still be True again and thus the statement will be executed again. This will keep on happening and as you might have guessed there will be no end for this loop. Such kind of looping is called infinite loop and should be avoided in programs.

Time for another example:

i = 0
while i < 5:
	print ("i =", i)

In this case, in the first iteration condition i < 5 is checked, since 0 < 5, hence the statement is executed. During execution, value of i is incremented by 1.

The for loop, is frequently used for iterating elements of a list, while loop on the other hand, is capable of serving several purposes, and it can iterate a list too! The logic is pretty much similar for accessing an element using indices. Run the loop from 0 to len(myList) and simply access the elements. And, there will be no need of using range() or xrange() function.

myList = [8, 9, 2, 3, 4, 6]
i = 0
while i < len(myList):
    print (myList[i])
    i = i+1;

Quickly going through the example for lists within a list:

bigList = [[1, 3, 6], [8, 2,], [0, 4, 7, 10], [1, 5, 2], [6]]
i = 0
j = 0
while i<len(bigList):
	while j<len(bigList[i]):
		print (“Element of list within a list -”,bigList[i][j])

The continue keyword

continue keyword is used inside the loops for altering the loop execution. Using continue inside the loop will skip the current statement execution, and it will check the condition again. Suppose there is a string,

>>> name = "StudyTonight"

So let's have a quick example demonstrating use of continue keyword:

for i in name:
	print (i)

It will print nothing. Let's see why? In the first iteration, first element of the list name will be picked, i.e. "S", the next statement inside the for loop is continue, thus as soon as this keyword is found, the execution of rest of the for loop statements is skipped and the flow gets back to the for loop starting to get the next element and check the condition. Same steps are followed by the next element of our string, i.e., "t" and the continue interrupts the flow again, and this will happen everytime the execution flow reaches the continue keyqord.

So, now if we want to write a program with a loop which prints only the lowercase letters of the string stored in the name variable, then, we can use the continue keyword to skip those letters which are not lowercase.

for i in name:
	if not i.islower():
	print (i)

if condition checks whether the element i is in lowercase, using islower() function. If it is not in lowercase then the rest of the statements are simply skipped and the print statement is never executed, although, if i is in lowercase then the if statement returns False and continue statement is not executed.

The continue keyword works in the exact same way for the while loop as well.

The break keyword

break keyword is used inside the loop to break out of the loop. Suppose while iterating over the characters of the string stored in the variable name, you want to break out of it as soon as the character "T" is encountered. This is how it can be done:

for i in name:
	if i == "T":
	print (i)

Now, as soon as the if condition gets the character "T", the compiler will execute the break statement and flow of execution will get out of the loop.