Python “in” operator speed

前端 未结 2 660
心在旅途
心在旅途 2021-01-17 15:08

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         


        
2条回答
  •  情歌与酒
    2021-01-17 15:48

    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.

提交回复
热议问题