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

╄→尐↘猪︶ㄣ 提交于 2020-01-13 19:43:57

问题


Just found out that both syntax ways are valid.

Which is more efficient?

element not in list

Or:

not element in list

?


回答1:


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



回答2:


When you're doing:

not x in y

And if x is in y, it will basically simplify to not True which is:

>>> not True
False

In the other hand, x not in y is just direct checking not in

To see the timings (always pretty similar):

>>> import timeit
>>> timeit.timeit(lambda: 1 not in [1,2,3])
0.24575254094870047
>>> timeit.timeit(lambda: not 1 in [1,2,3])
0.23894292154022878
>>> 

Also btw, not basically just do the opposite (if something is True, not will make it False, same point with the opposite

See not operator



来源:https://stackoverflow.com/questions/52048653/whats-more-efficient-in-python-key-not-in-list-or-not-key-in-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!