2

I am wondering, for education purposes, whether it's possible to rewrite all for loops in python as while loops. Theoretically, if and while is the minimum set of flow controls.

Searching around SO shows this question about range based for loops Converting for loops to while loops in python, which is obviously doable as the starting and ending indices are exposed. What about other forms of for loops? For example, what about looping through a list in its various forms?

2
  • Could you clarify "list in its various forms"? Commented Jan 24, 2016 at 14:34
  • @NadirSampaoli, e.g. for loop with a two-tuple as its iterator as in the second link provided. Also, performance difference between iterators/generators etc. is not a concern for me as I am interested only in the equivalence. Commented Jan 24, 2016 at 14:39

2 Answers 2

6

Yes, it is possible to do so, but it is probably not a good idea (some might say it is unpythonic).

When a for loop iterates over something that supports the iterator protocol, you can mimic its actions explicitly, and convert it to a while loop. E.g.,

l = [1, 2, 3]                                                                                                                                                                                          

it = iter(l)                                                                    
while True:                                                                     
    try:                                                                        
        print next(it)                                                       
    except StopIteration:                                                       
        break                  

I think this is terribly ugly :-)

Sign up to request clarification or add additional context in comments.

2 Comments

I think, the python-level description of the iterator types fits better here than the C API.
Thanks, @bereal - you are absolutely right! corrected.
3

To add to the answer by @AmiTavory - the problem is that in the general case you cannot know how many items a generator will yield, that's why you must except StopIteration when using a while loop. Consider the following example:

import random

def mygen(): # we don't know how many times this will yield
    while True:
        x = random.choice([1,2,3,4,5])
        if x == 3:
            break
        yield x

# proper way
for x in mygen():
    print x

print

# ugly way
g = mygen()
while True:
    try:
        print next(g)
    except StopIteration:
        break  

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.