Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic enumeration of while loop

Python has an elegant way of automatically generating a counter variable in for loops: the enumerate function. This saves the need of initializing and incrementing a counter variable. Counter variables are also ugly because they are often useless once the loop is finished, yet their scope is not the scope of the loop, so they occupy the namespace without need (although I am not sure whether enumerate actually solves this).

My question is, whether there is a similar pythonic solution for while loops. enumerate won't work for while loops since enumerate returns an iterator. Ideally, the solution should be "pythonic" and not require function definitions.

For example:

x=0
c=0
while x<10:
  x=int(raw_input())
  print x,c
  c+=1

In this case we would want to avoid initializing and incrementing c.

Clarification:

This can be done with an endless for loop with manual termination as some have suggested, but I am looking for a solution that makes the code clearer, and I don't think that solution makes the code clearer in this case.

like image 851
Bitwise Avatar asked Jun 16 '13 20:06

Bitwise


2 Answers

Improvement (in readability, I'd say) to Ignacio's answer:

x = 0
for c in itertools.takewhile(lambda c: x < 10, itertools.count()):
    x = int(raw_input())
    print x, c

Advantages:

  • Only the while loop condition is in the loop header, not the side-effect raw_input.
  • The loop condition can depend on any condition that a normal while loop could. It's not necessary to "import" the variables referenced into the takewhile, as they are already visible in the lambda scope. Additionally it can depend on the count if you want, though not in this case.
  • Simplified: enumerate no longer appears at all.
like image 103
morningstar Avatar answered Oct 15 '22 21:10

morningstar


Again with the itertools...

import itertools

for c, x in enumerate(
    itertools.takewhile(lambda v: v < 10,
      (int(raw_input()) for z in itertools.count())
    )
  ):
  print c, x
like image 42
Ignacio Vazquez-Abrams Avatar answered Oct 15 '22 22:10

Ignacio Vazquez-Abrams