1

I'm a bit confused, here, after "continue" is executed, it automatically jumps out of the current iteration and does not update the index, right?

def method(l):
    index = 0
    for element in l:

        #if element is number - skip it
        if not element in ['(', '{', '[', ']', '}', ')']:
            continue // THIS IS MY QUESTION
        index = index+1
        print("index currently is " + str(index)) 
    print("--------------------\nindex is : " + str(index))

t = ['4', '7', '{', '}', '(']
method(t)
2
  • 1
    Yes, you're correct Commented Oct 12, 2017 at 5:49
  • This is definitely an example of trying it in a simple console will help a tonne :). Commented Oct 12, 2017 at 5:49

2 Answers 2

4

The keyword continue skips to the next item in the iterator that you are iterating through.

So in you case, it will move to the next item in the list l without adding 1 to the index.

To give a simpler example:

for i in range(10):
   if i == 5:
      continue
   print(i)

which would skip to the next item when it gets to 5, outputting:

1
2
3
4
6
7
8
9
Sign up to request clarification or add additional context in comments.

Comments

2

continue moves to the next iteration of a loop.

When continue is executed, subsequent code in the loop is skipped as the loop moves to the next iteration where the iterator is updated. So for your code, once continue is executed, subsequent code (i.e., updating index and print) will be skipped as the loop will move to the next iteration:

for element in l:

    #if element is number - skip it
    if not element in ['(', '{', '[', ']', '}', ')']:
       continue # when this executes, the loop will move to the next iteration
    # if continue executed, subsequent code in the loop won't run (i.e., next 2 lines)
    index = index+1
    print("index currently is " + str(index))
print("--------------------\nindex is : " + str(index))

Therefore, after "continue" is executed, the current iteration ends without updating index.

Comments

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.