5

I'm new to Python, couldn't figure out the following syntax,

item = [0,1,2,3,4,5,6,7,8,9]
for element in item:
      if not element:
          pass
      print(element)

this gives me all of these element, it make sense as Pass is skip this step to next one

however if I use continue I will get the following

item = [0,1,2,3,4,5,6,7,8,9]
for element in item:
      if not element:
          continue
      print(element)
[1,2,3,4,5,6,7,8,9]

Can someone tell me why don't I get '0'? Is 0 not in the list?

Ry-
  • 218,210
  • 55
  • 464
  • 476
skybook
  • 89
  • 1
  • 6
  • 2
    `continue` skips the rest of the loop body and *continues* with the next iteration of the loop. `pass` does nothing at all. – Ry- Oct 25 '15 at 22:21
  • apart from the `pass/continue` conundrum which has been answered, what are you trying to achieve? There may be better ways to scan the list and produce the desired output (e.g. `filter(None, item)`) – Pynchia Oct 25 '15 at 22:33

3 Answers3

7

continue skips the statements after it, whereas pass do nothing like that. Actually pass do nothing at all, useful to handle some syntax error like:

 if(somecondition):  #no line after ":" will give you a syntax error

You can handle it by:

 if(somecondition):
     pass   # Do nothing, simply jumps to next line 

Demo:

while(True):
    continue
    print "You won't see this"

This will skip the print statement and print nothing.

while(True):
    pass
    print "You will see this" 

This will keep printing You will see this

Ahsanul Haque
  • 10,676
  • 4
  • 41
  • 57
3
  • "pass" just means "no operation". it does not do anything.
  • "continue" breaks a loop and jumps to the next iteration of the loop
  • "not 0" is True, so your "if not element" with element=0 triggers the continue instruction, and directly jumps to next iteration: element = 1
Stephane Martin
  • 1,612
  • 1
  • 17
  • 25
1

pass is a no-op. It does nothing. So when not element is true, Python does nothing and just goes on. You may as well leave out the whole if test for the difference that is being made here.

continue means: skip the rest of the loop body and go to the next iteration. So when not element is true, Python skips the rest of the loop (the print(element) line), and continues with the next iteration.

not element is true when element is 0; see Truth Value Testing.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343