Loops are one of the most basic entities inside a given programming language. With loop statements, we can execute a given piece of code till a certain condition is fulfilled. Once the condition becomes false, the program will then stop iterating over the loop statement. It will then execute the code after the loop statement. We can use loops to iterate over a given sequence, such as a list, a dictionary, a tuple, etc., or we can use it to execute a piece of code repeatedly. If you are new to python, then this article will be great for you in order to understand the difference between the two loops in python – for vs while loop.
For vs While Loop in Python
|Basis of Comparison||For Loop||While Loop|
|Format||Initialization, condition checking, and iteration statements are written at the top||Only initialization and condition checking is written at the top|
|Use Case||When you already know the number of iterations||When you don’t know the number of iteration.|
|Iteration||Every element is fetched through the iterator/generator. Example, range()||Every element is explicitly incremented or decremented by the user|
|Generator Support||For loop can be iterated on generators in Python.||While loop cannot be iterated on Generators directly.|
|Disassembly||For loop with range() uses 3 operations. range() function is implemented in C, so, its faster.||While loop with incrementing variable uses 10 operations. i+=1 is interpreted, hence, it’s slower than range()|
|Speed (May Vary on Conditions)||On basis of disassembly, for loop is faster than while loop.||On basis of disassembly, the while loop is slower than for loop.|
Types of loops in Python
In python, we have two different loop statements in order to loop over a piece of code in two different ways. They have the same functionality – i.e., they will execute a certain piece of code only if a condition is met. Yet, they differ in syntax and some other aspects.
- While loop – This loop statement checks for a condition at the beginning and till the condition is fulfilled, it will execute the body of the loop.
- For loop – For loops are used to sequentially iterate over a python sequence. When the sequence has been iterated completely, the for loop ends and thus executes the next piece of code.
The While Loop In Python
The while loop statement is used to repeat a block of code till a condition is fulfilled. When we don’t know the exact number of times, a loop statement has to be executed. We make use of while loops. This way, till the test expression holds true, the loop body will be executed.
The syntax of python’s while loop is:
while condition: #The loop body
The ‘condition’ will be the criteria based on which the loop body will be executed. Till the condition holds true, the loop body is executed. As soon as it becomes false, python will stop executing the loop body.
Let us understand with the help of an example.
n = int(input("Enter number N :")) sum = 0 temp = n while n > 0 : sum = sum + n n = n - 1 print("Sum of",temp,"numbers is:",sum)
Here, the above code is for printing the sum of n numbers as entered by the user. We don’t know here what will be the number that the user will enter. So, we shall use a while loop in order to print the sum of ‘n’ numbers. First, we take ‘n’ as input from the user. Then we have two variables, ‘sum’ , which will calculate the total summation and ‘temp’ for storing the value of ‘n’.
Inside the while loop, the condition to be fulfilled is that the value of ‘n’ should always be greater than zero. Inside the loop, we add the value of ‘n’ to ‘sum’ and then decrement ‘n’. While the value of ‘n’ will become zero, the while loop will stop executing and then print the ‘sum’ variable.
The output is:
Enter number N :15 Sum of 15 numbers is: 120
The For Loop In Python
The for loop in python is used to iterate over a given sequence. The sequence can be a string, a list, a tuple, a set, a dictionary, etc. As long as the length of the sequence is not reached, it will iterate over that sequence. The for loop contains initialization, the test expression, and the increment/decrement expression in the C language. Whereas in the case of python, we only have to mention the value and the sequence to be iterated.
The syntax of for loop in python is:
for value in sequence: #The loop body
Here, the value can be either an iterable or a sequence item. If it is an index, we use the range() function instead of the sequence. Otherwise, we can mention the sequence.
Example of for loop:
color = ['black', 'white', 'gray'] for item in color: print(item)
Here, we have taken a simple example to show the usage of a for loop. We have a list named ‘color’, which contains three colors. Then we use a for loop where we pass ‘item’, which represents each individual item in the sequence, and ‘color’ as the list sequence, which has to be traversed. Inside the for loop, we will print each ‘item’.
The output will be each list element printed one at a time.
black white gray
If we want to iterate using indexing, we can achieve that using the range() function.
color = ['black', 'white', 'gray'] for index in range(len(color)): print(color[index])
Here, we pass the sequence ‘color’ length as an argument to the range() function. Using the ‘index’, we print each individual sequence element.
The output is:
black white gray
For loop vs while loop python
The for loop and while loop are two different approaches to executing the loop statements in python. They both serve the same functionality of looping over a python code till a condition is being fulfilled. For loops and while loops differ in their syntax. In while loops, we have to mention only the condition before starting the loop. Whereas in the case of for loops, we have to mention the iterable as well as the sequence over which we iterate.
We use while loops when we don’t know the number of times we want to loop over a code, but we know the condition which determines the execution of the loop body. Whereas for loops are particularly used to iterate over a sequence. When you know the number of times the loop has to be executed, then using a range function in for loop, we can achieve that.
for vs while loop Python [Speed Comparison]
Byte Code Approach
We cannot depend on inner timer modules on how the while loop and for loop performs in python. There are many external factors that come into account.
Disassembly is a detailed breakdown of how each piece of code performs in Python. After disassembling using dis module, we can get to know that while loop has 10 operations if you are incrementing a variable in it and checking condition. Whereas, for loop has 3 operations for looping through range() function.
As a result, using dissassembly, you can clearly observe that for loop with range() function is clearly faster than the while loop with increment method.
Let us take two examples for iterating over a sequence – one using for loop and the other using while loop. We shall determine the speed using the time() method present on the time module.
Program for finding time taken by the for loop :
import time start = time.time() color = ['black', 'white', 'gray', 'red', 'green', 'blue', 'yellow', 'orange'] for index in range(len(color)): print(color[index]) end = time.time() print(end-start)
black white gray red green blue yellow orange 0.0034780502319335938
Program for the time taken by the while loop:
import time start = time.time() color = ['black', 'white', 'gray', 'red', 'green', 'blue', 'yellow', 'orange'] i = 0 while i != len(color): print(color[i]) i = i + 1 end = time.time() print(end-start)
black white gray red green blue yellow orange 0.007262706756591797
Here, we can see that the time taken for executing the while loop over the same sequence is more than the time taken for executing the for loop.
That wraps up the comparison between for vs while loop in python. If you have any questions in your mind, do let us know in the comments below.
Until next time, Keep Learning!