Loops in Python

As one of the most basic functions in programming, loops are an important piece to nearly every programming language. Loops enable developers to set certain portions of their code to repeat through several loops, referred to as iterations. This topic covers using multiple types of loops and applications of loops in Python.

For loops

for loops iterate over a collection of items, such as list or dict, and run a block of code with each element from the collection.

for i in [0, 1, 2, 3, 4]: print(i)

The above for loop iterates over a list of numbers.

Each iteration sets the value of i to the next element of the list. So first it will be 0, then 1, then 2, etc. The output will be as follow:

0
1
2
3
4

Range Function in for Loops

The range is a function that returns a series of numbers under an iterable form. Thus it can be used in for loops:

for i in range(5): print(i)
0 
1 
2 
3 
4

Gives the same result as the first for loop. Note that 5 is not printed as the range here is the first five numbers counting from 0.

Also, Read: Data Types in Python.

for loop can iterate on any iterable object, which is an object which defines a getitem or an iter function. The iter function returns an iterator, which is an object with a next function that is used to access the next element of the iterable.

Iterating over lists

To iterate through a list, you can use for:

for x in ['one', 'two', 'three', 'four']: print(x)
one 
two 
three 
four

This will print out the elements of the list.

The range function generates numbers which are also often used in a for loop:

for x in range(1, 6): print(x)
1 
2 
3 
4 
5

If you want to loop through both the elements of a list and have an index for the elements, you can use Python’s enumerate function:

for index, item in enumerate(['one', 'two', 'three', 'four']): print(index, '::', item)
0 :: one 
1 :: two 
2 :: three 
3 :: four

While Loops

A while loop will cause the loop statements to be executed until the loop condition is false. The following code will execute the loop statements a total of 4 times:

i = 0 while i < 4: #loop statements i = i + 1 print(i)
1
2
3
4

While the above loop can easily be translated into a more elegant for loop, while loops are useful for checking if some condition has been met. If the condition is always true, the while loop will run forever (infinite loop) if it is not terminated by a break or return statement or an exception:

while True: print "Infinite loop"

Break and Continue in Loops

When a break statement executes inside a loop, control flow “breaks” out of the loop immediately:

i = 0 while i < 7: print(i) if i == 4: print("Breaking from loop") break i += 1
0 
1 
2 
3 
4 
Breaking from loop

The loop conditional will not be evaluated after the break statement is executed. Note that break statements are only allowed inside a loop, syntactically. A break statement inside a function cannot be used to terminate loops that called that function.

break statements can also be used inside for loops:

for i in (0, 1, 2, 3, 4): print(i) if i == 2: break
0 
1 
2

Note that 3 and 4 are not printed since the loop has ended.

A continue statement will skip to the next iteration of the loop, bypassing the rest of the current block but continuing the loop. As with break, continue can only appear inside a loop:

for i in (0, 1, 2, 3, 4, 5): if i == 2 or i == 4: continue print(i)
0 
1 
3 
5

I hope you liked this article on Loops in python, feel free to ask your valuable questions in the comments section below. You can also follow me on Medium to learn everything in Machine Learning.

Get Daily Newsletters

Leave a Reply