Home > Software engineering >  Python Stay on Element In For Loop
Python Stay on Element In For Loop

Time:09-17

I'd like to know how I can somehow stay on one Element until the next loop cycle in a for loop. here's a code example:

for element in numbers:
    try:
        ...
    except:
        # It should stay on this element for the next time
        pass

So as example, I have

numbers = ['apple', 'banana', 'peach']

Now I'm on the element Banana as example, and If that error comes up, It should just stay on banana until the next cycle, so the expected output would be: apple, banana (error), banana (now It tries again), peach

I can explain In more detail If needed.

CodePudding user response:

That's not possible with regular for loops as far as I know. You can get something similar by controlling the iterating variable directly:

i = 0
while i < len(numbers):
  try:
    # Do work
    numbers[i] ....
    i  = 1
  except:
    # Don't increment i
    pass

Just be careful because you can get stuck in infinite loops with this if "banana" never succeeds.

CodePudding user response:

Use a while loop to iterate on the indexes:

i = 0
while i < len(numbers):
    element = numbers[i]
    try:
        ...
        i =1
    except:
        # It should stay on this element for the next time
        pass

CodePudding user response:

You could do that with a simple while loop inside the for loop:

for element in numbers:
    while True:
        try:
            ...
            break  # Success; break out of the while to the next element.
        except:
            # It should stay on this element for the next time
            pass

CodePudding user response:

You could put a while inside the for to keep processing the element until you are happy. This could end up in an infinite loop, so code wisely.

numbers = ['apple', 'banana', 'peach']

i_hate_bananas = True

for element in numbers:
    while True:
        try:
            if i_hate_bananas and element == 'banana':
                raise ValueError(f'{element}, yuck')
            print("I like", element)
            break
        except ValueError as e:
            print(e)
            i_hate_bananas = False
print('done')

This may be better than just having a single while and increment an indexer to numbers because it works with iteration and thus with any iterable.

  • Related