Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Complexity of *in* operator in Python

People also ask

What is the complexity of in operator in Python?

The average time complexity of the in operator for sets is O(1) . It does not depend on the number of elements. The execution time does not change depending on the value to look for. If you want to repeat in operation for a list with many elements, it is faster to convert it to a set in advance.

What is time complexity of set in Python?

Creating Set:- In Python, Sets are created through set() function. An Empty list is created. Note that empty Set cannot be created through {}, it creates dictionary. Checking if an item is in : Time complexity of this operation is O(1) on average.

What is time complexity of sort function in Python?

Sorting. The Python list sort() has been using the Timsort algorithm since version 2.3. This algorithm has a runtime complexity of O(n. logn).

What is the time complexity of MAP in Python?

map(function, iterable, ...) returns a list by applying function taking iterable as argument. So, time complexity is \text{len(iterable)}\cdot \text{complexity of function}.


The complexity of in depends entirely on what L is. e in L will become L.__contains__(e).

See this time complexity document for the complexity of several built-in types.

Here is the summary for in:

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

The O(n) worst case for sets and dicts is very uncommon, but it can happen if __hash__ is implemented poorly. This only happens if everything in your set has the same hash value.


It depends entirely on the type of the container. Hashing containers (dict, set) use the hash and are essentially O(1). Typical sequences (list, tuple) are implemented as you guess and are O(n). Trees would be average O(log n). And so on. Each of these types would have an appropriate __contains__ method with its big-O characteristics.