tags:

views:

425

answers:

6

Hi, Im currently finding problems in when should I use the While loop or the For loop in python. What looks like is that people prefer using the For loop (less code lines?), is there any specific situation wich I should use one or the other? Its a matter of personal preference? Or the codes I had read so far made me think wrong, and currently there are big differences beetween then?

Thanks

+3  A: 

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
So we could say that the 'While' is more of a deprecated thing in python?
fabio
@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
+7  A: 

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()
Konrad Rudolph
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
+1 This is a good answer too.
Andrew Hare
+21  A: 

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). 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.

S.Lott
+1 This is what I *wanted* to say :)
Andrew Hare
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
A: 

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
+1  A: 

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
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
+1  A: 

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