When to use “while” or “for” in Python

I am finding problems in when I should use a while loop or a for loop in Python. It looks like people prefer using a for loop (less code lines?). Is there any specific situation which I should use one or the other? Is it a matter of personal preference? The codes I have read so far made me think there are big differences between them.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.

Method 2

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

Method 3

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

Method 4

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.

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

Method 6

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.

Method 7

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

Method 8

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

Method 9

If your data is dirty and it won’t work with a for loop, you need to clean your data.

Method 10

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x