Junior — Middle
What is the time complexity of searching for an element in a list?
sobes.tech AI
Answer from AI
The time complexity of searching for an element in a list depends on the type of list:
-
In a regular Python list, which is implemented as a dynamic array, searching for a value is a linear search operation, i.e., O(n), where n is the number of elements.
-
If data structures such as sets or dictionaries are used, key-based search is performed in amortized O(1) time.
Example of linear search in a list:
my_list = [10, 20, 30, 40]
value = 30
if value in my_list:
print("Found")
Here, the operation value in my_list requires iterating over the elements until a match is found, which gives a time complexity of O(n).