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)):
    ...
6
  • 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. Commented Mar 28, 2022 at 10:07
  • Did you mean: for i in count():? Commented Mar 28, 2022 at 10:07
  • itertools.count is probably what you're looking for. it = count() next(it) Commented Mar 28, 2022 at 10:10
  • @deceze Yes there's probably a better approach, but it was just an easy example of while + enumeration. Commented Mar 28, 2022 at 10:32
  • @deceze I finally found an interesting solution with enumerate, a bit similar to stackoverflow.com/a/67265142 but slightly different, can we reopen this question? Commented Mar 28, 2022 at 10:44

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.