Hey there, readers, Hope you are doing great. In this article I am going to talk about the fastest way to loop in python and compare two widely used loops:
- While loop and
- For loop.
So, as you know, almost every programming language provides a concept of the loop, which helps us execute a set of instructions up to a desired number of times or in some cases infinitely.
Before jumping into the comparison between the While loop and the For loop one must know about their basic properties and how they work.
1. While Loop:
For any programming language, the concept of a while loop is the same. With While loop, we can execute a set of instructions as long as a condition is true.
The syntax of while loop in python goes like this:
i = 1 while i < 6: print(i) i += 1
As you can see in the above code the variable i initialized as 1 and increases by 1 with each iteration of the while loop, but the while loop will only run as long as i is less than 6 or up to 5.
1 2 3 4 5
Not only numbers while loop can depend upon any condition as long as the output of the condition is a boolean.
2. For Loop:
For loop is used to iterate over any kind of sequence. (i.e., a list, a tuple, a dictionary, a set, or a string).
The syntax for For loop in python goes like this:
fruits = ["apple", "banana", "cherry"] for x in fruits: print(x)
As you can see in this example that “fruits” is a list variable and the for loop will iterate through each list element and print it out.
apple banana Cherry
for x in range(6): print(x)
Here in this example, we are using the range() function with For loop to loop through a set of code a specified number of times.
range() function returns a sequence of numbers starting from 0 (default), and increases by 1(default), and ends at a specified number in our case that is 5 as we iterating through 0 to 6.
0 1 2 3 4 5
If you look closely, then you can see that While loop and For loop, both need a variable that initializes from a certain value, both require an end value to stop and both require a condition.
Now, this condition is syntactically different for each of these loops.
We can do similar kinds of tasks using both of these loops. But the problem is how do we choose between these two loops depending on their execution speed.
I have written two different functions to do the same job: the sum of the first n-1 numbers but one using For loop and another using the While loop.
The code is given below:
import timeit """ Sum the numbers from 0 to n-1 in different ways. """ def while_loop(n=100_000_000): i = 0 s = 0 while i < n: s += i i += 1 return s def for_loop(n=100_000_000): s = 0 for i in range(n): s += i return s def main(): print('while loop\t\t', timeit.timeit(while_loop, number=1)) print('for pure\t\t', timeit.timeit(for_loop, number=1)) if __name__ == '__main__': main()
In this code, I am using the timeit module to measure the time taken by these two loops to do the same job.
while loop 7.249936300000001 for pure 4.9734301
As you can see, For loop is faster than the while loop. Why is that?
The unfortunate fact is that compared to the c programming language that python is written in Python itself is an extremely slow language. To do the For loop python passes the iteration off to C code that works with the iterator of the range() function. So all of the iteration part of it is actually done in C all the bounds checking and incrementing of this variable, i is done in C. The only statement is done in Python is s += i. That is why it is Fast.
But in the case of the while loop both the conditional statement and incrementing i both of those things are done in python, not in C. But for loop uses 1 statement use C equivalent to these 2 statements which are using python in case of while loop, and obviously, s+=i is also using Python. That is why it is Slow.
We can do one more test to prove the above analysis.
Let’s add the i+=1 statement in the for loop function just to check the time.
The changed for loop function:
def for_loop(n=100_000_000): s = 0 for i in range(n): s += i i+=1 return s
while loop 7.2249926 for increment 8.3781583
Now the for loop is slower than the while loop. Adding one statement which uses python is slowing down the for loop function.
By the way, there are a much faster way to add first (n-1) numbers, which is the mathematical formula:
But in real life, we don’t use loops only for adding numbers, we use them for reading from the sequence and writing into the sequence.
Now you know why For loop is faster than While Loop. Now Whenever you will use loops consider using For loop, if possible.
Hope you find this article helpful. Let me know in the comments what is your view on this.
Always be creative.