Python | for vs while loop

Last Updated : 17 Jul, 2026

In Python, both for and while loops are used to execute a block of code repeatedly, but they are designed for different situations. Understanding the difference between them helps to choose the most appropriate loop for a given problem.

For loop

for loop is used to iterate over the elements of an iterable, such as a list, tuple, string, dictionary, or range(). It automatically retrieves each element one by one, making it the preferred choice when iterating over a collection of data.

Python
fruits = ["Apple", "Mango", "Orange"]
for fruit in fruits:
    print(fruit)

Output
Apple
Mango
Orange

Explanation: for loop visits each element in fruits one at a time. During each iteration, the current element is assigned to fruit and printed.

Below is the flowchart of For loop:

forloop

While Loop

while loop repeatedly executes a block of code as long as a specified condition remains True. It is commonly used when the number of iterations is not known beforehand and the loop should continue until a condition changes.

Python
count = 1
while count <= 3:
    print(count)
    count += 1

Output
1
2
3

Explanation: loop continues while count <= 3 is True. After each iteration, count is increased by 1. When count becomes 4, the condition becomes False and the loop stops.

Below is the flowchart of While loop:

ff

The table below highlights the key differences between for and while loops.

Featurefor Loopwhile Loop
PurposeIterates over a sequence or iterableRepeats while a condition is True
Number of IterationsUsually known in advanceMay or may not be known in advance
ConditionControlled by the iterableControlled by a Boolean condition
Best Used WhenProcessing every element in a collectionRepeating until a condition changes
Counter UpdateHandled automatically during iterationUsually updated manually inside the loop
Common UseLists, tuples, strings, dictionaries, range()Input validation, menu-driven programs, unknown repetitions
Comment
Morty Proxy This is a proxified and sanitized view of the page, visit original site.