Difference between for loop and while loop in Python
At a glance, the difference is simple:
- For loop: runs a fixed number of times, usually when you already know how many times you want the code to repeat.
- While loop: runs until a condition becomes false, which is useful when you don’t know in advance how many times it should run.
For loop in Python
Python For Loops are used for iterating over a sequence like lists, tuples, strings and ranges.
- For loop allows you to apply the same operation to every item within loop.
- Using For Loop avoid the need of manually managing the index.
- For loop can iterate over any iterable object, such as dictionary, list or any custom iterators.
For Loop Example:
s = ["Geeks", "for", "Geeks"]
# using for loop with string
for i in s:
print(i)
Output
Geeks for Geeks
Python for Loop Flowchart

While Loop in Python
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.
While Loop Example:
# Python example for while loop
count = 0
while (count < 3):
count = count + 1
print("Hello Geek")
Output
Hello Geek Hello Geek Hello Geek
Python while Loop Flowchart

Comparison Table
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. |