0

Is there some way to move the index forward in a for loop in python? For example, if I'm iterating through a string and find some char that I'm looking for, can I begin reading from that position on the next iteration of the for loop?

Like, after reading an x, read until a y and start from the position following the y on the next iteration:

for i in range(len(myString)):
  if myString[i] == 'x':
    j = i + 1
    while( myString[j] != '\n' ):
      if( myString[j] == 'y' ):
        i = j + 1  # start at position following y in string on the next iteration
      j = j + 1

Or do I have to use a while loop to achieve this?

8
  • 1
    I believe you'd have to use a while loop, or use the keyword continue in the case that you want to ignore. Commented Jan 18, 2016 at 23:00
  • 2
    Possible duplicate of python arbitrarily incrementing an iterator inside a loop Commented Jan 18, 2016 at 23:01
  • 1
    Nope, definitely not a duplicate, @JGreenwell - none of the examples there deal with reversing an iterator Commented Jan 18, 2016 at 23:06
  • Okay, I guess a while loop it is. Thanks for the feedback. Commented Jan 18, 2016 at 23:06
  • 1
    Possible duplicate of Readable, controllable iterators? Commented Jan 18, 2016 at 23:16

3 Answers 3

2

You can use an string instead of list in this sample code. It finds the first x in the remaining part of the list, then finds the first y after that 'x' and so on

#mylist = [list to search]
i = 0
while true:
    list_to_search = mylist[i:]
    if 'x' not in list_to_search:
        break
    j = list_to_search.index('x')
    if 'y' not in list_to_search[j+1:]:
        break
    i = list_to_search.index('y')
    (x_pos,y_pos)  = (j,i)
    #your code
Sign up to request clarification or add additional context in comments.

1 Comment

@ alivar Nice. I didn't think to use splicing.
1

You could try using an infinite loop:

while true:
   if i >= len(myString): # Exit condition
      break

   # do something with myString[i]

   # set i as you want

2 Comments

@ Christian That's a nice alternative. I'll give it a go. Thanks.
I think that should be if i >= len(myString). Otherwise it goes out of bounds when i == len(myString). Otherwise, this works well for my purposes.
1

Now, effectively you're still using a while loop here - but I think this comes closer in spirit to what you were thinking about:

def myrange(limit=0):
    counter = 0
    while counter < limit:
        next = yield counter
        try:
            counter = int(next) - 1
        except TypeError:
            counter += 1    


mylist = ['zero', 'one', 'two', 'five', 'four']       
my_iter = myrange(len(mylist))

for i in my_iter:
    print(mylist[i])
    if mylist[i] == 'five':
        print('-- three, sir! --')
        mylist[i] = 'three!'
        my_iter.send(i)
    elif mylist[i] == 'four':
        print("Don't count that number!")

This works because of the send function that generators have. They allow you to send a value to the generator that the generator can then use how it wishes. Note that when you call .send() on a generator that it will yield the next value (so when we call my_iter.send(i), it's actually yielding the next value. That's why we call counter = int(next) - 1. The alternative would be to put the -1 in your for loop.

1 Comment

@ Wayne Werner I'm pretty new to python, so I think this example is a bit above my pay grade for now. I'll definitely play around with it though. Thanks for the feedback.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.