Python “in” operator speed

自作多情 提交于 2019-12-19 17:42:26

问题


Is the in operator's speed in python proportional to the length of the iterable?

So,

len(x) #10
if(a in x): #lets say this takes time A
    pass

len(y) #10000
if(a in y): #lets say this takes time B
    pass

Is A > B?


回答1:


A summary for in:

list - Average: O(n)
set/dict - Average: O(1), Worst: O(n)

See this for more details.




回答2:


There's no general answer to this: it depends on the types of a and especially of b. If, for example, b is a list, then yes, in takes worst-case time O(len(b)). But if, for example, b is a dict or a set, then in takes expected-case time O(1) (i.e., constant time).

About "Is A > B?", you didn't define A or B. As above, there's no general answer to which of your in statements will run faster.



来源:https://stackoverflow.com/questions/20234935/python-in-operator-speed

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