When to use "while" or "for" in Python
Asked Answered
E

11

52

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.

Ebony answered 28/5, 2009 at 12:44 Comment(2)
Isn't this question automatically generalized to all languages or why the restriction to python?Aborigine
@Aborigine In 2009 when the question was asked, languages with a Python-style for (sometimes called foreach in other languages) had a significantly lower market share, and it was still very common to think of for as very simple syntactic sugar on while - 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
C
92

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.

Cooe answered 28/5, 2009 at 12:55 Comment(4)
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.Ebony
@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.Cooe
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.Weissman
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.Basophil
E
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()
Expressway answered 28/5, 2009 at 12:55 Comment(1)
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? ThanksEbony
B
18

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
Bingle answered 28/5, 2009 at 12:46 Comment(2)
So we could say that the 'While' is more of a deprecated thing in python?Ebony
@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.Whidah
C
10

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.

Chophouse answered 16/10, 2019 at 9:42 Comment(0)
B
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)

Behest answered 28/5, 2009 at 13:32 Comment(2)
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 WhileEbony
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.Libel
C
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.

Clap answered 28/5, 2009 at 19:56 Comment(1)
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.Salivation
S
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
Sunglasses answered 28/5, 2009 at 13:17 Comment(0)
C
1

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.

Cleavage answered 29/6, 2023 at 16:45 Comment(0)
F
0

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

  1. goto, if
  2. switch\elif function call (this includes recursion)
  3. while, until, continue, break
  4. for
  5. 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.

Foreshore answered 19/4, 2024 at 1:31 Comment(0)
M
-2

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

Medico answered 27/8, 2020 at 20:51 Comment(2)
Please add an explanation as to why that is.Mannes
This is not clear - I have no idea what "normal loop" is supposed to mean. Aside from that, existing answers from 2009 seem to cover the material perfectly well.Frobisher
D
-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.

Downfall answered 13/8, 2021 at 19:4 Comment(1)
Please provide more details to your answer - what are the cases / why would you prefer one over the other?Corinnacorinne

© 2022 - 2025 — McMap. All rights reserved.