Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python "in" operator speed

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?

like image 767
Anshu Dwibhashi Avatar asked Nov 27 '13 05:11

Anshu Dwibhashi


People also ask

How fast is the in operator Python?

Is the in operator's speed in Python proportional to the length of the iterable? Yes. The time for in to run on a list of length n is O(n) . It should be noted that it is O(1) for x in set and x in dict as they are hashed, and in is constant time.

Are Python set operations fast?

set is as fast as it gets. However, if you rewrite your code to create the set once, and not change it, you can use the frozenset built-in type. It's exactly the same except immutable. If you're still having speed problems, you need to speed your program up in other ways, such as by using PyPy instead of cPython.

What does the IN operator do for lists?

In Python, the in operator determines whether a given value is a constituent element of a sequence such as a string, array, list, or tuple. When used in a condition, the statement returns a Boolean result of True or False. The statement returns True if the specified value is found within the sequence.

Is Python in efficient?

In a survey of the energy efficiency of 27 programming languages, C tops the list, and Python was the second most inefficient.


2 Answers

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.

like image 104
Tim Peters Avatar answered Sep 22 '22 11:09

Tim Peters


A summary for in:

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

See this for more details.

like image 21
lennon310 Avatar answered Sep 23 '22 11:09

lennon310