Introduction to Loop in Python

We provide instructions to our computers to perform specific tasks, which can sometimes be repetitive. For example, if we have a hundred elements in a list and want to remove the last element 50 times. In that case, we must repeat the same instruction of removing the last element 50 times. But writing the same instruction 50 times will make the code too lengthy and not easily understandable. 

To do this programmatically, programmers designed the technique of loops where we do not need to write instructions n times, to repeat it for n times. In this article, we will learn the details of this technique and the types of loops used in Python.

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 frequently used?
  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() function in Python creates a “range” data type to maintain a sequence of integers in the defined range. This range is passed as an input to the range function. 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. Also, 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. 

Now, 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.

This range function will be used in later parts of this blog. Hence we discussed this earlier. Now, let's bring ourselves to the main topic of this article, i.e. loops.

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 from the given list,
  2. Add 1 to it,
  3. Update the values of that element.

These three sets of tasks are repetitive and will be exactly the same for every element in the list. If N elements are in the given list, beginners can write these repetitive instructions N times to operate for adding 1. But this will make our program very lengthy.

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

list = [1, 2, 3, 4, 5, 6]

for every element in list, add 1 to it and update the value.

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.

Diagram representing For and While loop in python

For Loop in Python

Taking 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]

We know from the list properties that we can access elements at the ‘ith’ index by writing as example_list[i]. To add 1 to elements present at every index, we need to perform three 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

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 from 0 to 6. 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. It made the code look much short in length.

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 accessed the elements present at that index, and in the second, we directly accessed the elements without knowing their index values. But, sometimes, we need to access both (elements and index values). 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)

If you are still getting familiar with the condition and branching concept in Python, please look at this blog.

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, we check the validity of the condition that the index value should equal the integer value formed from the range function. If that is satisfied, we perform the 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 exit the loop. 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

With “for loop,” we executed instructions for N (already known) times. But there can be scenarios where we might not be sure about this number N. In simple terms, we do not know how many times to repeat the execution. 

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, 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 the value of ‘idx’ is not changing, and the condition for idx<10 is always 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 loop of programs. These statements are often used in ML and Data Science applications, so let's see.

Continue Statement 

We know that our code line-wise executes our program, which means the instruction present at line 7 will be executed after the instruction present at line number 6. Continue bypasses the instructions coming after the ‘continue’ line inside the loop. For example:

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

“Continue” is present in line 3, so the above code did not execute the print statement in line 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 Statement

The break statement exits 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 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.

Use of Loops in Machine Learning and Data Science

We might not find any ML or Data Science application without the loop concept involved. Some of the most commonly used areas of the loop in ML are:

  1. While training our ML models, we define how many times machines will see the same dataset. Let’s say machines are seeing the dataset 100 times. Then the same operation will be performed 100 times where the concept of loop will be used.
  2. In Data Science, we need to process the dataset. For this, we go through each sample present in the data, and for that, we use the loop.
  3. Once we train a model and host it over the cloud so that people can interact with that, we continuously test our model on the inputs provided by users. Here, the concept of loop becomes handy.

Conclusion

Loop is an important concept in any programming language. It makes the program cleaner and easily accessible. In this article, we learned the basics of loops in Python and their two types: For loop and While loop, frequently used in data science and machine learning projects. Last, we discussed using “continue and break” statements. We hope you find the article enjoyable.

Enjoy Learning! Enjoy Algorithms!

More from EnjoyAlgorithms

Self-paced Courses and Blogs