0

I sometimes have this:

i = 0
while condition:
    ...
    i += 1

Here is an example situation: Create file but if name exists add number.

I don't know any option to do another way (except those discussed in Using enumerate function in while loops), but usually Python always has some syntactic sugar to avoid the manual "i = 0, ..., i += 1 pattern".

Is there an alternative in newest versions of Python? Something like (pseudo-code):

for i in enumerate(while(condition)):
    ...
Basj
  • 41,386
  • 99
  • 383
  • 673
  • There's probably a better approach to this overall…?! E.g.: `glob` all existing file names, sort them, pick the one with the highest number, split it, use the number + 1. – deceze Mar 28 '22 at 10:07
  • Did you mean: `for i in count():`? – quamrana Mar 28 '22 at 10:07
  • [`itertools.count`](https://docs.python.org/3/library/itertools.html#itertools.count) is probably what you're looking for. `it = count()` `next(it)` – deceze Mar 28 '22 at 10:10
  • @deceze Yes there's probably a better approach, but it was just an easy example of while + enumeration. – Basj Mar 28 '22 at 10:32
  • @deceze I finally found an interesting solution with `enumerate`, a bit similar to https://stackoverflow.com/a/67265142 but slightly different, can we reopen this question? – Basj Mar 28 '22 at 10:44
  • @deceze The context makes that it doesn't really apply to https://stackoverflow.com/questions/9884213/looping-from-1-to-infinity-in-python but it might work here. Can I post? (community wiki is ok) – Basj Mar 28 '22 at 10:56

0 Answers0