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?

2
  • 2
    continue skips the rest of the loop body and continues with the next iteration of the loop. pass does nothing at all. Commented Oct 25, 2015 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)) Commented Oct 25, 2015 at 22:33

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.