The Python Oracle

Is there a difference between continue and pass in a for loop in Python?

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: RPG Blues Looping

--

Chapters
00:00 Is There A Difference Between Continue And Pass In A For Loop In Python?
00:21 Accepted Answer Score 533
00:50 Answer 2 Score 38
01:06 Answer 3 Score 115
01:29 Answer 4 Score 17
01:56 Thank you

--

Full question
https://stackoverflow.com/questions/9483...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #syntax #continue

#avk47



ACCEPTED ANSWER

Score 533


Yes, they do completely different things. pass simply does nothing, while continue goes on with the next loop iteration. In your example, the difference would become apparent if you added another statement after the if: After executing pass, this further statement would be executed. After continue, it wouldn't.

>>> a = [0, 1, 2]
>>> for element in a:
...     if not element:
...         pass
...     print(element)
... 
0
1
2
>>> for element in a:
...     if not element:
...         continue
...     print(element)
... 
1
2



ANSWER 2

Score 115


Yes, there is a difference. continue forces the loop to start at the next iteration while pass means "there is no code to execute here" and will continue through the remainder of the loop body.

Run these and see the difference:

for element in some_list:
    if not element:
        pass
    print(1) # will print after pass

for element in some_list:
   if not element:
       continue
   print(1) # will not print after continue



ANSWER 3

Score 38


continue will jump back to the top of the loop. pass will continue processing.

if pass is at the end for the loop, the difference is negligible as the flow would just back to the top of the loop anyway.




ANSWER 4

Score 17


There is a difference between them,
continue skips the loop's current iteration and executes the next iteration.
pass does nothing. It’s an empty statement placeholder.
I would rather give you an example, which will clarify this more better.

>>> some_list = [0, 1, 2]
... for element in some_list:
...     if element == 1:
...         print "Pass executed"
...         pass
...     print element
... 
0
Pass executed
1
2

... for element in some_list:
...     if element == 1:
...         print "Continue executed"
...         continue
...     print element
... 
0
Continue executed
2