2

How can I repeat an index of a for loop?

for path in directory:
   
   ...
   
   if ...:
      stop here and
      repeat the current index of the for loop
   ...

I would call it a restart ^^

  • 2
    The concept you're looking for is `redo`, which is a keyword in Perl and Ruby that does exactly what you want. Unfortunately, Python has no equivalent feature. – Silvio Mayolo Sep 03 '21 at 23:59
  • 1
    You need a do-while loop, which, sadly, does not exist in Python either. So, replace it with a `while` loop: `X; while condition: X`. – DYZ Sep 04 '21 at 00:05

1 Answers1

1
for path in directory:
   X
   if C:
      stop here and
      repeat the current index of the for loop
   Y

becomes

for path in directory:
   while True:
      X
      if not C:
         break
   Y
no comment
  • 6,381
  • 4
  • 12
  • 30
  • 2
    That is so horrifyingly messy but... yeah, it's the correct way to do this control flow pattern in general in Python. I'd suggest refactoring to avoid it at all costs, but this is the correct answer. – Silvio Mayolo Sep 04 '21 at 00:12
  • 1
    @SilvioMayolo I guess we could also wrap `directory` in an iterator that has a `.redo()` method, that would allow their way... – no comment Sep 04 '21 at 00:14
  • 1
    @SilvioMayolo Oh nice, someone [already did](https://stackoverflow.com/a/36575610/16759116) exactly that. – no comment Sep 04 '21 at 00:21