Comparing for vs while loop in Python (2022)

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 ComparisonFor LoopWhile Loop
Declarationfor object in sequence:
while condition:
FormatInitialization, condition checking, and iteration statements are written at the topOnly initialization and condition checking is written at the top
Use CaseWhen you already know the number of iterationsWhen you don’t know the number of iteration.
IterationEvery element is fetched through the iterator/generator. Example, range()Every element is explicitly incremented or decremented by the user
Generator SupportFor loop can be iterated on generators in Python.While loop cannot be iterated on Generators directly.
DisassemblyFor 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.

  1. 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.
  2. 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

Comparing for vs while loop in Python (1)

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 = 0temp = nwhile n > 0 : sum = sum + n n = n - 1print("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 :15Sum of 15 numbers is: 120

The For Loop In Python

Comparing for vs while loop in Python (2)

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:

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.


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:



4 Methods to Get Python File Size Easily

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.

Practical Approach

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 timestart = 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)



Program for the time taken by the while loop:

import timestart = time.time()color = ['black', 'white', 'gray', 'red', 'green', 'blue', 'yellow', 'orange']i = 0while i != len(color): print(color[i]) i = i + 1end = time.time()print(end-start)



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!

Trending Right Now

  • Python class Vs module: Differences and Comparison
  • Python Unittest Vs Pytest: Choose the Best
  • PIP vs PIP3: What is the Difference?
  • Differences Between Pyglet and Pygame in Python

You might also like

Latest Posts

Article information

Author: Laurine Ryan

Last Updated: 09/06/2022

Views: 5493

Rating: 4.7 / 5 (77 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Laurine Ryan

Birthday: 1994-12-23

Address: Suite 751 871 Lissette Throughway, West Kittie, NH 41603

Phone: +2366831109631

Job: Sales Producer

Hobby: Creative writing, Motor sports, Do it yourself, Skateboarding, Coffee roasting, Calligraphy, Stand-up comedy

Introduction: My name is Laurine Ryan, I am a adorable, fair, graceful, spotless, gorgeous, homely, cooperative person who loves writing and wants to share my knowledge and understanding with you.