48

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.

starball
  • 20,030
  • 7
  • 43
  • 238
Fabio
  • 1,113
  • 2
  • 14
  • 19
  • Isn't this question automatically generalized to all languages or why the restriction to python? – YuZ May 05 '23 at 13:28

10 Answers10

89

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.

user668074
  • 1,111
  • 10
  • 16
S.Lott
  • 384,516
  • 81
  • 508
  • 779
  • I think I got it, like the example Konrad made. Its more a matter of readability, you can use both iterations but its prefereable to use the While for a more vague data structure. – Fabio May 28 '09 at 13:05
  • 6
    @fabio: "Its more a matter of readability". No. It's a matter of matching algorithm and data structure. There's no thinking or any "prefereable". It's simple. **Use for unless it's impossible.** If for is impossible for some reason, then **while**. – S.Lott Nov 24 '10 at 18:57
  • 3
    It's one thing to say it, another to show it. You should have shown an example where "for" doesn't work, but "while" does. I can say they are exactly the same, and then how does anyone know which of us is correct? Examples help explain things much better. – Wayne Filkins Jul 19 '20 at 00:33
  • There's no need to be dogmatic. While their built-in semantics differ, it is obvious that any `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. – Nathan Chappell Sep 22 '22 at 09:31
24

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()
Neuron
  • 5,141
  • 5
  • 38
  • 59
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • 2
    If its not a problem and just a matter of curiosity, you said that I could write a for statement to replace that while loop, how would that looks like? Thanks – Fabio May 28 '09 at 13:06
16

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
Andrew Hare
  • 344,730
  • 71
  • 640
  • 635
  • So we could say that the 'While' is more of a deprecated thing in python? – Fabio May 28 '09 at 12:48
  • 4
    @fabio ... not quite. There are loops that can only reasonably be written using while, but for the most part you should try to use for in preference to while. – Aaron Maenpaa May 28 '09 at 12:51
9

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.

DINA TAKLIT
  • 7,074
  • 10
  • 69
  • 74
5

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)

Adrian Mester
  • 2,523
  • 1
  • 19
  • 23
  • Great advice, btw I think the main reason I had this doubt was coz I came from PHP wich never saw any clear difference beetween the FOR and While – Fabio May 28 '09 at 14:08
  • 1
    For loops are used when you want to do operations on each member of a sequence, in order. While loops are used when you need to: operate on the elements out-of-order, access / operate on multiple elements simultaneously, or loop until some condition changes from True to False. – apraetor Apr 18 '16 at 16:53
3

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.

Robert Rossney
  • 94,622
  • 24
  • 146
  • 218
  • 2
    Skipping over items in the list can be done with continue. The reason I would use this style of while loop is if I wanted to conditionally retrieve the next item in the loop before starting over at the beginning of the loop. – Anthony Lozano Jun 19 '14 at 19:17
2

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
Ants Aasma
  • 53,288
  • 15
  • 90
  • 97
0

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.

-2

while loop is better for normal loops for loop is much better than while loop while working with strings, like lists, strings etc.

-2

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.

  • 1
    Please provide more details to your answer - what are the cases / why would you prefer one over the other? – d1sh4 Aug 13 '21 at 20:39