When I should use a while
loop or a for
loop in Python? It looks like people prefer using a for
loop (for brevity?). Is there any specific situation which I should use one or the other? Is it a matter of personal preference? The code I have read so far made me think there are big differences between them.
Yes, there is a huge difference between while and for.
The for statement iterates through a collection or iterable object or generator function.
The while statement simply loops until a condition is False.
It isn't preference. It's a question of what your data structures are.
Often, we represent the values we want to process as a range
(an actual list), or xrange
(which generates the values) (Edit: In Python 3, range
is now a generator and behaves like the old xrange
function. xrange
has been removed from Python 3). This gives us a data structure tailor-made for the for statement.
Generally, however, we have a ready-made collection: a set, tuple, list, map or even a string is already an iterable collection, so we simply use a for loop.
In a few cases, we might want some functional-programming processing done for us, in which case we can apply that transformation as part of iteration. The sorted
and enumerate
functions apply a transformation on an iterable that fits naturally with the for statement.
If you don't have a tidy data structure to iterate through, or you don't have a generator function that drives your processing, you must use while.
for
can be written with a while
(get the iterator and deal with it manually), and any while
can be written with a for
(create a contrived iterator that checks the while-condition and raises StopIteration
-- or whatever the protocol is). In practical cases, for
offers the benefit of "guaranteed termination" and can be very concise, the while
offers "programmatic termination", but is typically less concise because termination is explicit. –
Basophil while
is useful in scenarios where the break condition doesn't logically depend on any kind of sequence. For example, consider unpredictable interactions:
while user_is_sleeping():
wait()
Of course, you could write an appropriate iterator to encapsulate that action and make it accessible via for
– but how would that serve readability?¹
In all other cases in Python, use for
(or an appropriate higher-order function which encapsulate the loop).
¹ assuming the user_is_sleeping
function returns False
when false, the example code could be rewritten as the following for
loop:
for _ in iter(user_is_sleeping, False):
wait()
The for
is the more pythonic choice for iterating a list since it is simpler and easier to read.
For example this:
for i in range(11):
print i
is much simpler and easier to read than this:
i = 0
while i <= 10:
print i
i = i + 1
for loops is used when you have definite itteration (the number of iterations is known).
Example of use:
- Iterate through a loop with definite range:
for i in range(23):
. - Iterate through collections(string, list, set, tuple, dictionary):
for book in books:
.
while loop is an indefinite itteration that is used when a loop repeats unkown number of times and end when some condition is met.
Note that in case of while loop the indented body of the loop should modify at least one variable in the test condition else the result is infinite loop.
Example of use:
The execution of the block of code require that the user enter specified input:
while input == specified_input:
.When you have a condition with comparison operators:
while count < limit and stop != False:
.
Refrerences: For Loops Vs. While Loops, Udacity Data Science, Python.org.
First of all there are differences between the for loop in python and in other languages. While in python it iterates over a list of values (eg: for value in [4,3,2,7]), in most other languages (C/C++, Java, PHP etc) it acts as a while loop, but easier to read.
For loops are generally used when the number of iterations is known (the length of an array for example), and while loops are used when you don't know how long it will take (for example the bubble sort algorithm which loops as long as the values aren't sorted)
Consider processing iterables. You can do it with a for
loop:
for i in mylist:
print i
Or, you can do it with a while
loop:
it = mylist.__iter__()
while True:
try:
print it.next()
except StopIteration:
break
Both of those blocks of code do fundamentally the same thing in fundamentally the same way. But the for
loop hides the creation of the iterator and the handling of the StopIteration
exception so that you don't need to deal with them yourself.
The only time I can think of that you'd use a while
loop to handle an iterable would be if you needed to access the iterator directly for some reason, e.g. you needed to skip over items in the list under some circumstances.
For loops usually make it clearer what the iteration is doing. You can't always use them directly, but most of the times the iteration logic with the while loop can be wrapped inside a generator func. For example:
def path_to_root(node):
while node is not None:
yield node
node = node.parent
for parent in path_to_root(node):
...
Instead of
parent = node
while parent is not None:
...
parent = parent.parent
A for loop will iterate through a list (a range being a list of numbers).
A while loop will iterate until a condition is met.
You could step through a file word by word using a for loop and make an exception using a break. As others have mentioned, you normally expect to make it through the list when using for loops.
for word in book:
if word == 'is':
break
A while loop runs until the exception occurs. As others have mentioned, there is no expectation of iterating through all values when using a while loop.
print("Enter any negative value to end.")
while (n=int(input)) => 0:
grade_total += n
average = grade_total / n
This would allow different students to be graded with different number of gradable items.
As with ALL languages you should try to use the most specific tool for the job.
while condition
are a very general construct
for item in iterator
is a bit more specific.
Whenever you can use the latter it is preferred. In a more general sense we have hierarchy of concepts
goto
,if
switch\elif
function call
(this includes recursion)while
,until
,continue
,break
for
map
,filter
,reduce
You want to use the lowest PART (i.e. highest index) of the list to succinctly express your ideas.
If you can implement an operation as a map
, there's no need to write a for
or while
loop. If you can express something as a for
or while
loop succinctly there's no need to write the concept using recursion. If you can use function calls and loops to express an idea succinctly there is no need to invoke a goto
.
Complex ideas need you to go higher up the list (i.e. to more primitive ideas).
Not everyone is just mapreducing a bunch of data. They are doing some complex operations FOR Each element so they need to live in level (4) and not level (5).
Some people are looping on a condition that is highly complex and NOT indexed by some iterator. They need to stay in while
land.
Some people are working on a highly self referential thing with many cases that has many interwoven parts, they need to live in function
and switch
land.
Sometimes, (but very very rarely), you need code that that literally JUMPS around because either 1. for some reason THAT IS THE SIMPLEST way to express your idea or 2. You have some resource/space constraint that forces you to implement it, 3. You are optimizing beyond what the compiler can determine.
In these rare circumstances you want to live in goto
land.
Here we see that Python prefers for
over while
where possible as it respects the natural hierarchy of making ideas more specific.
while loop is better for normal loops for loop is much better than while loop while working with strings, like lists, strings etc.
For me if your problem demands multiple pointers to be used to keep
track of some boundary I would always prefer While loop.
In other cases it's simply for loop.
© 2022 - 2025 — McMap. All rights reserved.
for
(sometimes calledforeach
in other languages) had a significantly lower market share, and it was still very common to think offor
as very simple syntactic sugar onwhile
- see also Why should I use foreach instead of for (int i=0; i<length; i++) in loops?. Nowadays, people who actually need an answer are quite likely to be beginners who are learning Python as their first programming language - simply because of how successful Python has been. – Frobisher