2

Assuming one has a string like so:

my_line = 'this is a line of text\n'

and wants to check for the absence of a word, e.g., the word 'row'.

Is there any difference between using:

a) if not 'row' in my_line:

and

b) if 'row' not in my_line:

Are the two exactly the same in this case? Is there any case in which the two diverge?

Ma0
  • 15,057
  • 4
  • 35
  • 65

1 Answers1

3

They are identical, you can see this from the dis CPython bytecode output:

>>> import dis
>>> def f1():                              
...     if not 'row' in my_line: pass
... 
>>> def f2(): 
...     if 'row' not in my_line: pass
... 
>>> dis.dis(f1)
  2           0 LOAD_CONST               1 ('row')
              2 LOAD_GLOBAL              0 (my_line)
              4 COMPARE_OP               7 (not in)
              6 POP_JUMP_IF_FALSE        8
        >>    8 LOAD_CONST               0 (None)
             10 RETURN_VALUE
>>> dis.dis(f2)
  2           0 LOAD_CONST               1 ('row')
              2 LOAD_GLOBAL              0 (my_line)
              4 COMPARE_OP               7 (not in)
              6 POP_JUMP_IF_FALSE        8
        >>    8 LOAD_CONST               0 (None)
             10 RETURN_VALUE
Chris_Rands
  • 38,994
  • 14
  • 83
  • 119
  • As stated in [answer], please avoid answering unclear, overly-broad, typo, unreproducible, or duplicate questions. Write-my-code requests and low-effort homework questions are off-topic for [so] and more suited to professional coding/tutoring services. Good questions adhere to [ask], include a [mcve], have research effort, and have the potential to be useful to future visitors. Answering inappropriate questions harms the site by making it more difficult to navigate and encouraging further such questions, which can drive away other users who volunteer their time and expertise. – TigerhawkT3 Apr 03 '17 at 09:37
  • @TigerhawkT3 The question is fine, but yes, it is a duplicate, but I didn't know that when I answered; we all miss duplicates sometimes, particularly when the titles are quite different :) – Chris_Rands Apr 03 '17 at 09:40