Sobes.tech
Junior — Middle

What is the average time to delete an element by key in a Python dictionary?

sobes.tech AI

Answer from AI

In Python, a dictionary (dict) is implemented based on a hash table, so the operation of deleting an element by key is on average performed in O(1) — constant time. This means that the deletion time does not depend on the size of the dictionary.

Example of deleting an element:

my_dict = {'a': 1, 'b': 2, 'c': 3}
del my_dict['b']  # delete by key 'b'
print(my_dict)  # {'a': 1, 'c': 3}

However, in the worst case (for example, with a large number of hash collisions), the time can increase, but such situations are rare thanks to good hash function implementations.

What is the average time to delete an element by key… - sobes.tech