2c2c
2c2c

Reputation: 4864

conditionally stop iteration of for loop in python

In a typical C-like language a for loop gives you more control over iteration. I'm wondering how to do the equivilent

for(int i = 0; i < A.length; i++) {
  do_things(A[i]);
  if (is_true(i)) {
    i--;
  }
}

in Python?

In other languages I opt to use their container based for loop constructs, but they typically have vanilla for loops that I can use for situations like this. How do I get more "control" when iterating in Python?

I imagine the answer to this is very basic, but the search terms are muddied with other questions.

Upvotes: 1

Views: 1739

Answers (1)

Chris
Chris

Reputation: 22953

The best equivalent in Python would be a while-loop:

i = 0
while i < A.length: # If `A` is a regular Python container type, use `len()`
    do_things(A[i])
    if  is_true(i):
        i -= 1
    i += 1

Note however, as said in the comments, iterating like this over a container is more often than not, a bad idea. You should review your code and make sure you actually need this behavior.


EDIT

It's just a sloppy explanation of a loop that doesnt continue to the next element until some condition is met. I didn't explain clear enough I guess

Use continue instead then. Decrementing i is the wrong action:

i = 0
while i < A.length:
    do_things(A[i])
    if not is_true(i):
        continue
    i += 1

Better yet, you can ditch the while-loop all together and use enumerate:

for i, el in enumerate(A):
    if not is_true(el):
        continue
    # do work

Upvotes: 1

Related Questions