Open In App

Difference between for loop and while loop in Python

Last Updated : 24 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn about the difference between for loop and a while loop in Python. In Python, there are two types of loops available which are for loop and while loop. The loop is a set of statements that are used to execute a set of statements more than one time. For example, if we want to print “Hello world” 100 times then we have to write a print statement 100 times which is a tedious task but with the help of loops we can do it in just a few lines of code. In this article, we will learn both types of loops separately and then their differences.

Difference between for loop and while loop in Python

For Loop Vs While Loop Banner

For loop in Python

In Python, a for loop is used to iterate over a sequence of items, such as a Python tuple, list, string, or range. The loop will execute a block of statements for each item in the sequence.

Python for Loop Flowchart

For loop in Python

For Loop Flow chart

Syntax of Python for loop

In the below syntax for is a keyword, var is the variable name, and iterable is an object which can be looped over or iterated over with the help of a for a loop. Objects like tuples, lists, sets, dictionaries, strings, etc. are called iterable. We can also use the range() function in place of iterable.

for var in iterable:

   # statements

Python for Loop (With Examples)

In the below example, we have created a list of items and then iterate through the list using for loop to print the items in the list.

Python3




# Create a list of items
items = ['pen', 'notebook',
         'pencil', 'lunch box']
  
# Run a loop to print
# items in a list
for item in items:
  print(item)


Output:

pen
notebook
pencil
lunch box

While Loop in Python

In Python, a while loop is used to repeatedly execute a block of statements while a condition is true. The loop will continue to run as long as the condition remains true.

Python while Loop Flowchart

While Loop in Python

While Loop Flow chart

 

Syntax of Python While loop

In the while loop condition is written just after the ‘while’ keyword and then we write the set of statements to perform some task.

while condition:

    # Set of statements

Python while Loop (With Examples)

In this example, we are using a while loop to perform the task that we have done in the example of for loop. Here, after declaring the items list we initialize the index with 0 and store the length of the items list in the variable ‘items_len’ after that running a while loop in which we have given a condition that runs the loop until the value of the index is less than items_len. Inside the while loop, we print the items of the items list using indexing and increment the value of the index by 1 to iterate over the list. 

Python3




# Create a list of items
items = ['pen', 'notebook',
         'pencil', 'lunch box']
  
# Declare a index
index = 0
  
# Store length of items list
items_len = len(items)
  
# Run a loop to print
# items in a list
while index<items_len:
  print(items[index])
  index = index+1


Output:

pen
notebook
pencil
lunch box

When no condition is given in the for and while loop?

In this case, when the condition is not given they will run into an infinite loop.

Python For Loop:

Python3




a = [1]
for i in a:
    print("GFG")
    a.append(i)


Python While Loop:

Python3




while True:
    print("GFG")


Both of the loops will run for infinite times and print GFG.

Difference between for loop and while loop in Python

Now, we will compare both loops in Python to understand where to use ‘for loop’ and where to use ‘while loop’.

For loop

While loop

For loop is used to iterate over a sequence of items.

While loop is used to repeatedly execute a block of statements while a condition is true.

For loops are designed for iterating over a sequence of items. Eg. list, tuple, etc.

While loop is used when the number of iterations is not known in advance or when we want to repeat a block of code until a certain condition is met.

For loop require a sequence to iterate over.

While the loop requires an initial condition that is tested at the beginning of the loop.

For loop is typically used for iterating over a fixed sequence of items

While loop is used for more complex control flow situations.

For loop is more efficient than a while loop when iterating over sequences, since the number of iterations is predetermined and the loop can be optimized accordingly.

While a loop may be more efficient in certain situations where the condition being tested can be evaluated quickly.



Similar Reads

Loop Through a List using While Loop in Python
In Python, the while loop is a versatile construct that allows you to repeatedly execute a block of code as long as a specified condition is true. When it comes to looping through a list, the while loop can be a handy alternative to the more commonly used for loop. In this article, we'll explore four simple examples of how to loop through a list us
3 min read
Decrement in While Loop in Python
A loop is an iterative control structure capable of directing the flow of the program based on the authenticity of a condition. Such structures are required for the automation of tasks. There are 2 types of loops presenting the Python programming language, which are: for loopwhile loop This article will see how to decrement in while loop in Python.
3 min read
Python While Loop
Python While Loop is used to execute a block of statements repeatedly until a given condition is satisfied. When the condition becomes false, the line immediately after the loop in the program is executed. Syntax of while loop in Pythonwhile expression: statement(s)Flowchart of Python While Loop While loop falls under the category of indefinite ite
7 min read
Python Program to Find the Sum of Natural Numbers Using While Loop
Calculating the Sum of N numbers in Python using while loops is very easy. In this article, we will understand how we can calculate the sum of N numbers in Python using while loop. Calculate Sum of Natural Numbers in Python Using While LoopBelow are some of the examples by which we can see how we can calculate the sum of N numbers in Python: Exampl
2 min read
How to Kill a While Loop with a Keystroke in Python?
Loops are fundamental structures in Python programming for executing a block of code repeatedly until a certain condition is met. However, there are scenarios where you might want to terminate a while loop prematurely, especially when you want to give the user the ability to interrupt the loop with a keystroke. In this article, we'll explore some s
3 min read
Multiplication Table Using While Loop in Python
Multiplication tables are fundamental in mathematics, serving as the building blocks for more advanced concepts. In Python, we can use various methods to generate multiplication tables, and one versatile tool for this task is the 'while' loop. In this article, we will explore some commonly used and straightforward methods to create multiplication t
3 min read
How to Parallelize a While loop in Python?
Parallelizing a while loop in Python involves distributing the iterations of a loop across multiple processing units such as the CPU cores or computing nodes to execute them concurrently. This can significantly reduce the overall execution time of the loop, especially for tasks that are CPU-bound or require heavy computation. In this article, we'll
2 min read
How to Emulate a Do-while loop in Python?
We have given a list of strings and we need to emulate the list of strings using the Do-while loop and print the result. In this article, we will take a list of strings and then emulate it using a Do-while loop. Do while loop is a type of control looping statement that can run any statement until the condition statement becomes false specified in t
3 min read
Loops in Python - For, While and Nested Loops
Python programming language provides two types of Python loopshecking time. In this article, we will look at Python loops and understand their working with the help of examp - For loop and While loop to handle looping requirements. Loops in Python provides three ways for executing the loops. While all the ways provide similar basic functionality, t
9 min read
Difference between for loop in C and Python
For loops, in general, are used for sequential traversal. It falls under the category of definite iteration. Definite iterations mean the number of repetitions is specified explicitly in advance. However, there is a difference in working of c and python for loop, though both are used for iterations the working is different. For Loop in C For loop i
3 min read
Article Tags :
Practice Tags :