Introduction to Loop in Python

Programs are the sequence of instructions we provide to computers in their understandable language. While writing these instructions, we might have encountered scenarios where we need to repeat some instructions n number of times or until some condition is not satisfied. To do this programmatically, programmers designed the looping technique, which is widely used today. Here we do not need to write instructions n times, to repeat it for n times. In this article, we will learn various loops used in Python and building Machine Learning or Data Science projects.

Key Takeaways from this Blog

After successfully going through this blog, we will be able to understand the following things:

  1. What is the ‘range’ function in Python?
  2. What is a loop in Python?
  3. What are the types of loops we need to know in Python?
  4. How can we make conditional loops in Python?
  5. Use of Continue and Break statements in a loop.

So let’s begin our journey with the first question, i.e.,

What is the range function in Python?

range() is one of the most important and widely used python functions. It is used to create a “range” data type that contains a sequence of integers in the defined range passed as inputs. We give a starting index corresponding to the start integer of the range and the ending index corresponding to the ending integer for the range. For example, range(5,10) creates a “range” data type that contains integers 5, 6, 7, 8, and 9. Please note that the last integer will not be included.

>>> range(5,10)
# range(5, 10)

If we pass just one integer as the input to this range function, it will consider 0 as the default starting index. For example, range(3) will result in a range data type sequence containing 0, 1, and 2. Also, suppose we pass three integers as the input to this function. In that case, it will treat the first integer as the start index, the second integer as the end index, and the third integer as the allowed gap between two consecutive integers. For example, range(1,10,2) will contain a sequence containing 1, 3, 5, 7, and 9. If nothing is passed as a third integer, it considers +1 the default gap. 

We can also design a sequence in reverse order by mentioning the third integer as a -ve integer. For example, range(5, -5, -2) will result in a sequence containing 5, 3, 1, -1, and -3. An invalid pair of integers will result in an empty sequence. For example, range(5, 3) is an invalid pair as the start index is lesser than the end index with the default gap between two integers as +1.

What is a loop in Python?

Let’s understand this with an example. Suppose a list contains N integers, and we aim to add 1 to all the elements in that list. Here, we need to perform three tasks, 

  1. Pick one element once at a time present in the list,
  2. Add 1 to it
  3. Update the values of that element

These three sets of tasks are repetitive and will be the same for every element in the list. Suppose there are N elements in the given list; then, any programmer can write these repetitive instructions N times to perform the operation of adding 1. But this will make our program very lengthy.

To solve this issue, the concept of the loop comes into the picture, which gives us the flexibility to execute repetitive instructions N times by just writing it in the program once.

There are mainly two types of loops that are used very frequently in Python:

  1. For loop
  2. While loop

So let’s start with the “for” loop first.

For Loop in Python

Let’s take the same example of adding 1 to every element present in a list containing seven different elements.

example_list = [1, 2.5, 3.7, 7.11, 2, 3, 7]

As we know from the list properties, we can access elements present at the ‘ith’ index by writing as example_list[i]. To add 1 to elements present at every index, we need to perform three sets of instructions as discussed above.

  1. Pick one element once at a time present in the list,
  2. Add 1 to it
  3. Update the values of that element

Let’s first see a naive program where we will write the same instruction for every element.

For element at 0th index, example_list[0] = example_list[0] + 1
For element at 1st index, example_list[1] = example_list[1] + 1
For element at 2nd index, example_list[2] = example_list[2] + 1
For element at 3rd index, example_list[3] = example_list[3] + 1
For element at 4th index, example_list[4] = example_list[4] + 1
For element at 5th index, example_list[5] = example_list[5] + 1
For element at 6th index, example_list[7] = example_list[7] + 1

Indeed, it is not effective and lengthy as well. Now we will use the “for loop” to perform these instructions for every element in the list. 

1. Using the range function

If noticed carefully, the only variable in the above program is the index value which varies from 0 to 6. And we can use the range function to create this sequence starting from 0 to 6. Please note that we want to use 6, so the value that needs to be passed in the range function would be 7, not 6.

for i in range(7):
    example_list[i] = example_list[i] + 1
print(example_list)
# Output: [2, 3.5, 4.7, 8.11, 3, 4, 8]

Yes! That’s it :). The above code snippet will do the entire thing in just two lines. 

2. Without using the range function

We can directly access the elements without using the range function explicitly in the “for loop”. For example,

new_list = []

for element in example_list:
    element = element + 1
    new_list.append(element)

print(new_list)
# Output: [2, 3.5, 4.7, 8.11, 3, 4, 8]

We have made an empty list and appended the modified elements. If we access elements like the above example, we treat the element as a separate entity, and the modification in this element will not affect the original list.

3. Using the enumerate function

In 1st method, we generated index values and then accessed the elements present at that index, and in the second, we directly accessed the elements without knowing their index values. But, sometimes, we might need to access elements and their index value. In such case, we can use enumerate function like this:

for i, element in enumerate(example_list):
    ...

The example use-case can be, suppose we want to add 1 to every element except the 3rd index. Here we need the information about the index also. We can use the Condition and Branching properties like this:

new_list = []
for i, element in enumerate(example_list):
    if i != 3:
       element = element + 1
    
    new_list.append(element)

The above code will add 1 to every element except the element present at the 3rd index, the 4th element in the example list, as indexing starts from 0 in Python.

Else statement with “For” loop

We can use the condition and branching concepts with loops as well. If noticed carefully, what exactly are we doing inside a loop? We are checking the validity of the condition. If that is satisfied, we are performing the same task, and once that condition breaks, we exit the loop. The same we saw with if-else statements. So, we can also use “else” with “for” loops, which will be executed once we finish the loop execution. For example:

lst = ['EnjoyAlgorithms', 'ML', 'DS', 'DSA']
for idx in range(len(lst)):
  print(lst[idx])
else:
  print("Exited from for loop")

# Output
EnjoyAlgorithms
ML
DS
DSA
Exited from for loop

While Loop in Python

Using the “for loop,” we executed a set of instructions for N (already known) times. But we can have scenarios where we might not be sure about this number N. We can also say this as we don’t know how often we must execute a set of operations because it depends upon a condition. For example, let’s say the elements of the example list represent money in dollars. And we want to donate this money to several persons starting from the 0th index. But our maximum donation amount is fixed, which is $15. So, we do not know the exact index where we need to stop. So in such a scenario, we will use a while loop like this:

tot_donation = 0
max_donation = 15
idx = 0
while tot_donation < max_donation:
      tot_donation = tot_donation + example_list[idx]
      idx = idx + 1

The use of a while loop can also work on conditioning. For example, suppose we want to perform a set of instructions until a condition is met. 

condition = True
while condition != False:
      execute instructions

The problem of infinite loop

From the above code snippet, we can sense that there can be scenarios when conditions are never fulfilled, and our program will fall inside an infinite loop scenario. In such a case, our code will not terminate until the execution exhausts our system’s memory. One common mistake while writing a while loop can be missing the index increment. For example:

idx = 0
while idx < 10:
    print(idx)

The above code will run forever because idx is not changing, and the condition for idx<10 will always be true. To rectify the mistake, we can increment the idx value slowly so that it progresses to make the statement of idx <10 false.

Else statement with while loop.

While loops also work on the concept of conditions and branching. When a condition is satisfied, we execute the while loop statements; whenever that condition breaks, we exit the loop. This is the same as if-else statements; hence, we can use else statements with a while loop. For example:

idx = 0
while idx<3:
      print("EnjoyAlgorithms")
      idx += 1
else:
      print("ML")
# Output
EnjoyAlgorithms
EnjoyAlgorithms
EnjoyAlgorithms
ML

Continue and Break Statements in a loop.

Continue and Break are two useful statements frequently used to bypass or terminate the looping of programs.

Continue

We know that our code line-wise executes our program, which means the instruction present at line 7 will be executed before the instruction present at line number 6. Continue is used to bypass the instructions coming after the line in which continue is written. For example:

for i in range(3):
  print("* ",i)
  continue
  print("# ",i+1)
# Output
* 0 
* 1 
* 2

“Continue” is present in line number 3, so the above code did not execute the print statement in line number 4, having a print statement with “#”. This can be useful if we do not want to execute instructions for some special conditions. As we saw, we want to add 1 to every element but not for the element present at the 3rd index. For that, we can use continue like this:

for i, element in enumerate(example_list):
      
    if i == 3:
       continue
    element = element + 1
    example_list[i] = element
    
print(example_list)

# [2, 3.5, 4.7, 7.11, 3, 4, 8]

Please note that the 3rd index element did not change as we placed a conditional continue statement for the 3rd index.

Break

The break statement is used to exit the loop once a certain condition is met. For example, suppose we are adding elements of the array, and if the sum exceeds 15, we will exit the loop and will not execute anything present in that loop. For example:

max_sum_limit = 15
total_sum = 0

for i, element in enumerate(example_list):
    total_sum = total_sum + element
    if total_sum >= max_sum_limit:
       break
    print(i)
    
# Output
0
1
2
3

Adding elements till the 4th index will make the total sum = 16.31, and it will satisfy the condition of totalsum >= maxsum_limit; hence “break” will be executed, and it will not print index values from the 4th index itself. Please note that the addition command will be executed for the 4th index, but it will not print the 4th index because before printing that index, we exited the loop using the break statement.

Conclusion

In this article, we learned the basics of loops in Python, which is required to build AI applications. We discussed two types of loops: For loop and While loop, which is frequently used in data science and machine learning projects. Last, we discussed “continue and break” statements in a loop. We hope you enjoyed the article.

Next Blog: Introduction to Function in Python

Previous Blog: Condition and Branching in Python

Enjoy Learning! Enjoy Algorithms!

Share feedback with us

More blogs to explore

Our weekly newsletter

Subscribe to get weekly content on data structure and algorithms, machine learning, system design and oops.

© 2022 Code Algorithms Pvt. Ltd.

All rights reserved.