Junior — Middle
How is the time to search for an element within a set in Python estimated?
sobes.tech AI
Answer from AI
In Python, a set is implemented based on a hash table, so the average search time for an element within a set is O(1) — constant time.
This means that the operation of checking for the presence of an element (for example, x in my_set) is very fast and does not depend on the size of the set.
However, in the worst case (for example, with a large number of hash collisions), the time can degrade to O(n), but such situations are extremely rare thanks to good hash function implementations.
Example:
my_set = {1, 2, 3, 4, 5}
if 3 in my_set:
print("Element found")