Search code examples
pythoncontinue

how does 'continue' work in this python code?


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)

Solution

  • 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