Reputation: 24516
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)
Upvotes: 1
Views: 166
Reputation: 471
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
.
Upvotes: 2
Reputation: 20434
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
Upvotes: 4