According to Python wiki: Time complexity, set is implemented as a hash table. So you can expect to lookup/insert/delete in O(1) average. Unless your hash table's load factor is too high, then you face collisions and O(n).
P.S. for some reason they claim O(n) for delete operation which looks like a mistype.
P.P.S. This is true for CPython, pypy is a different story.
Answer from Sergey Romanovsky on Stack OverflowAccording to Python wiki: Time complexity, set is implemented as a hash table. So you can expect to lookup/insert/delete in O(1) average. Unless your hash table's load factor is too high, then you face collisions and O(n).
P.S. for some reason they claim O(n) for delete operation which looks like a mistype.
P.P.S. This is true for CPython, pypy is a different story.
The other answers do not talk about 2 crucial operations on sets: Unions and intersections. In the worst case, union will take O(n+m) whereas intersection will take O(min(x,y)) provided that there are not many element in the sets with the same hash. A list of time complexities of common operations can be found here: https://wiki.python.org/moin/TimeComplexity
Time complexity of sets
Time complexity of python set operations?
What's the time complexity of set.add()?
python - What is time complexity of a list to set conversion? - Stack Overflow
Videos
I understand that sets are data structures where all its elements are sorted and it doesn't contain any duplicate values, but why is their time complexity just O(1)?
How can it be a constant value, even if the set contains millions of elements?
I thought that the complexity was O(n*log(n)) due to a binary search, but looks like it's even faster and I can't really understand how.
Thanks in advance for any answer!
Yes. Iterating over a list is O(n) and adding each element to the hash set is O(1), so the total operation is O(n).
I was asked the same question in my last interview and didn't get it right.
As Trilarion commented in the first solution, the worst-case complexity is O(n^2). Iterating through the list will need O(n), but you can not just add each element to the hash table (sets are implemented using hashtables). In the worst case, our hash function will hash each element to the same value, thus adding each element to the hash set is not O(1). In such a case, we need to add each element to a linked list - (note that hash sets have a linked list in case of collision). When adding to the linked list we need to make sure that the element doesn't already exist (as a Set by definition doesn't have duplicates). To do that we need to iterate through the same linked list for each element, which takes a total of n*(n-1)/2 = O(n^2).