Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's more efficient in Python: `key not in list` or `not key in list`? [duplicate]

Just found out that both syntax ways are valid.

Which is more efficient?

element not in list

Or:

not element in list

?

like image 319
Javier Novoa C. Avatar asked Jan 23 '26 20:01

Javier Novoa C.


1 Answers

They behave identically, to the point of producing identical byte code; they're equally efficient. That said, element not in list is usually considered preferred. PEP8 doesn't have a specific recommendation on not ... in vs. ... not in, but it does for not ... is vs. ... is not, and it prefers the latter:

Use is not operator rather than not ... is. While both expressions are functionally identical, the former is more readable and preferred.

To show equivalence in performance, a quick byte code inspection:

>>> import dis
>>> dis.dis('not x in y')
  1           0 LOAD_NAME                0 (x)
              2 LOAD_NAME                1 (y)
              4 COMPARE_OP               7 (not in)
              6 RETURN_VALUE

>>> dis.dis('x not in y')
  1           0 LOAD_NAME                0 (x)
              2 LOAD_NAME                1 (y)
              4 COMPARE_OP               7 (not in)
              6 RETURN_VALUE
like image 137
ShadowRanger Avatar answered Jan 26 '26 10:01

ShadowRanger