Open In App

Time Complexity of In Operator in Python

Last Updated : 02 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The in operator in Python is commonly used to check for membership within collections such as lists, sets, dictionaries and strings. Understanding the time complexity of the in operator is crucial for writing efficient code, especially when dealing with large datasets. In this article, we'll explore about different data structures and time complexity of using in operator with them.

Complexity of in operator in lists

Time Complexity: O(n)

Lists in Python are implemented as dynamic arrays. When you use the in operator to check if an element exists in a list, Python performs a linear search which means it iterates through each element of the list until it finds a match or reaches the end of the list.

Example:

Python
li= [1, 2, 3, 4, 5]
print(3 in li)  # True
print(6 in li)  # False

The time complexity is O(n) because in the worst case, the element might be at the end of the list or not present at all requiring a full traversal of all n elements.

Complexity of in operator in Sets

Time Complexity: O(1) on average

Sets in Python are implemented using hash tables. The in operator for sets leverages the hash function to determine if an element exists, providing average case constant time complexity.

Example:

Python
s= {1, 2, 3, 4, 5}
print(3 in s)  # True
print(6 in s)  # False

The average-case time complexity is O(1) because hash table lookups are generally fast. However, in the rare case of many hash collisions, the time complexity can degrade to O(n).

Complexity of in operator in Dictionaries

Time Complexity: O(1) on average

Similar to sets, dictionaries in Python are also implemented using hash tables. The in operator checks if a key exists in the dictionary, providing average case constant time complexity.

Example:

Python
dict = {'a': 1, 'b': 2, 'c': 3}
print('b' in dict)  # True
print('d' in dict)  # False

The average case time complexity is O(1) for key lookups due to the efficient hashing mechanism. However, in cases of excessive hash collisions, it could degrade to O(n).

Complexity of in operator in Strings

Time Complexity: O(m * n)

Strings in Python are arrays of characters. When using the in operator to check if a substring exists within a string, Python performs a substring search, which can be quite complex.

Example:

Python
s= "hello world"
print("world" in s)  # True
print("python" in s)  # False

The time complexity is O(m * n), where n is the length of the string and m is the length of the substring being searched for.


Next Article

Similar Reads