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 Overflow
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 72104506 โ€บ time-complexity-of-set-lookup
python - Time complexity of set lookup - Stack Overflow
It depends on the data, for example if your set contains string objects(Or any other objects that don't produce the same hash), then the time complexity of membership testing would be O(1). Hash of string objects are randomly generated for security ...
Discussions

Time complexity of python set operations?
Checking if set s is a subset of set t involves checking every element in s for membership in t. While these operations are O(1) on average, the worst-case time complexity can degrade to O(n) for operations like insertion, deletion, and lookup, particularly in scenarios with high collision rates in the hashing process. However, Python... More on designgurus.io
๐ŸŒ designgurus.io
1
10
June 21, 2024
Lookup time in a list vs. set
A quick tip when you perform a lot of membership testing operations (if element in collection_of_elements) - if you use a set instead of a list, it's going to be much faster. But converting a list to a set has some downsides - it takes time, and you might lose the initial ordering. Full article with benchmarks and more details can be found here: https://switowski.com/blog/membership-testing More on reddit.com
๐ŸŒ r/Python
6
11
October 12, 2020
Don't understand time complexity of this easy leetcode question
I think for Python sets, the average case of set lookup is O(1) since there are no duplicates. So O(1) nested in O(n) is linear time. More on reddit.com
๐ŸŒ r/learnpython
13
3
June 21, 2023
python - searching performance in list is better than in set - Stack Overflow
The test results are 48.3 msec ... in a set and contradicts the time complexity analysis. I tried increasing n and comparing the searching speed, and it turns out that the finding holds true until I get a memory error when n is very big. (base) PS C:\Users> python -m timeit ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ time complexity of sets
r/learnpython on Reddit: Time complexity of sets
March 17, 2021 -

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!

Top answer
1 of 3
2
Ok, so sets/dictionaries work by hashing the index value. So that it's a constant time to find the item. You don't iterate through the set/dictionary. You just simply ask what is the value at this address? Let's say there are a number of people living on a street, everyone lives at the address that matches the length of their last name, and I told you got go to "smith" You wouldn't spend time checking houses to find smith, you would immediately go to house 5. The constant time spent was converting smith to 5. It would take you the same constant time to find where Scot or Johnson lived. That's how a hash works, it converts whatever value you have into an address in memory. It gets a bit more complex than just "length" and there is code in place to handle collisions (smith and jones are not at the same address). But that's the simple version of it. I understand that sets are data structures where all its elements are sorted They're not sorted. They're unordered. In recent version of python dictionaries maintain "insertion order".
2 of 3
2
As others have pointed out, these are implemented with hash tables. Hashing is when you generate some pseudorandom number from some input data. In a hash table, that number is clipped (modulo) so as to fit inside the table. Ideally, different data will always get you a different number so you end up in the right spot of the hash table in constant time, but that's obviously not always going to happen and you will get so-called hash collisions. When those happen, some sort of strategy is necessary to deal with them and since you'd ideally design your hash table so they don't happen very often, that strategy tends to just be to use the next spot in the table, and then just linearly search. In that sense, it's not exactly a constant-time algorithm, but you really should only be searching a very small potion of the full table, so it's close. As the table fills up (its "load factor" increases), this cost generally grows, although that is not universally true (e.g., when perfect hashing is an option). It can also happen that the hash table needs to be grown, which will generally not be a constant-time operation. There are all sorts of strategies for that. More often than not, though, the hashing step will not lead to a collision, and you get O(1) performance.
๐ŸŒ
Python
wiki.python.org โ€บ moin โ€บ TimeComplexity
TimeComplexity - Python Wiki
As seen in the source code the complexities for set difference s-t or s.difference(t) (set_difference()) and in-place set difference s.difference_update(t) (set_difference_update_internal()) are different! The first one is O(len(s)) (for every element in s add it to the new set, if not in t).
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ internal-working-of-set-in-python
Internal working of Set in Python - GeeksforGeeks
July 11, 2025 - It's important to note that an ... exists in a set, you can use the in keyword. The average time complexity for this operation is O(1), but in the worst case, it can become O(n)....
๐ŸŒ
Code Like A Girl
code.likeagirl.io โ€บ time-complexities-of-python-dictionary-and-set-operations-ee13511a2881
Time Complexities of Python Dictionary and Set Operations | by Python Code Nemesis | Code Like A Girl
November 7, 2023 - This means that the time taken to search for an element in a set is independent of the size of the set. The O(1) time complexity for searching is achievable because sets in Python, similar to dictionaries, are implemented using hash tables, which provide fast lookup operations.
๐ŸŒ
Medium
medium.com โ€บ @abhishekjainindore24 โ€บ collections-searching-in-a-list-set-tuple-and-dictionary-and-binary-search-b6c10a108bc6
Collections, Searching in a list, set, tuple and dictionary and binary search | by Abhishek Jain | Medium
May 18, 2024 - The time complexity of searching for an element in a set is usually O(1), which means that it takes a constant amount of time to search for an element in a set, regardless of the size of the set.
Find elsewhere
๐ŸŒ
Reddit
reddit.com โ€บ r/python โ€บ lookup time in a list vs. set
r/Python on Reddit: Lookup time in a list vs. set
October 12, 2020 - If we compare this to a lookup in a set (which starts from around 27 nsec), I would say that no matter the size of a list, lookup in a set is faster (1-2 nsec of difference is probably less than the standard deviation of the benchmarks).
๐ŸŒ
w3reference
w3reference.com โ€บ blog โ€บ time-complexity-for-lookup-in-dictionary-values-lists-vs-sets
Python: Time Complexity of Lookup in `dictionary.values()` โ€“ Lists vs Sets (O(1) vs O(N) Explained)
List lookup time: 12.3456 seconds # O(N) scales with size Set lookup time: 0.0012 seconds # O(1) is nearly instant ยท Observation: The set lookup is ~10,000x faster! For larger dictionaries (e.g., 1 million entries), the gap widens further.
๐ŸŒ
Coding Confessions
blog.codingconfessions.com โ€บ confessions of a code addict โ€บ looking under the hood of python's set data structure
Looking Under the Hood of Python's Set Data Structure
October 14, 2024 - In most scenarios where sets are used, lookup is done much more frequently than insertion, which means that the implementation has to offer a fast lookup even if insertion is a tad bit slower. In the case of Pythonโ€™s set implementation they use a hash table (no surprises) underneath to power it. Hash tables offer constant time lookups in the average case, although as the table gets fuller, the performance can degrade unless careful measures are taken.
Top answer
1 of 3
8

My original comment, which I was asked to incorporate into this answer (good idea!): Lookup time accounts for very little of what you're timing. You're mostly timing how long it takes just to do the set(range(1000000)) and list(range(1000000)) parts. Building the set/list to begin with are far more expensive than the lookup. Use the -s argument to take the setup cost out of what you're timing.

Elaborating on my comment, and since other answers didn't show the use of -s, here it is:

$ python -m timeit -n 100 -s "n = 1; c = set(range(1000000))" "n in c"
100 loops, best of 5: 46 nsec per loop

$ python -m timeit -n 100 -s "n = 1; c = list(range(1000000))" "n in c"
100 loops, best of 5: 45 nsec per loop

$ python -m timeit -n 100 -s "n = 10000; c = set(range(1000000))" "n in c"
100 loops, best of 5: 60 nsec per loop

$ python -m timeit -n 100 -s "n = 10000; c = list(range(1000000))" "n in c"
100 loops, best of 5: 71.4 usec per loop

The code given to -s is not timed. It lets you set up objects for the timed code to use. n in c is the only code timed now.

2 of 3
4

I think set creation is taking most of the tim as it involves hashing each element, as mentioned by @tim-peters,.

Here, I have created set and list before performing a search operation and the search time seems to be a lot faster for sets than that of list.

import random
import timeit

def setup(n):
    data = list(range(n))
    random.shuffle(data)
    return set(data), data

def test_set(s, value):
    return value in s

def test_list(l, value):
    return value in l

n = 1000000
s, l = setup(n)

# Test with a value that's guaranteed to be in both
value_in = random.choice(l)

# Test with a value that's guaranteed not to be in either
value_out = n + 1

print("Searching for a value that exists:")
print("Set:", timeit.timeit(lambda: test_set(s, value_in), number=1000))
print("List:", timeit.timeit(lambda: test_list(l, value_in), number=1000))

print("\nSearching for a value that doesn't exist:")
print("Set:", timeit.timeit(lambda: test_set(s, value_out), number=1000))
print("List:", timeit.timeit(lambda: test_list(l, value_out), number=1000))

Result:

Searching for a value that exists:
Set: 0.00023545200008356915
List: 28.11379308300002

Searching for a value that doesn't exist:
Set: 0.0002436169999100457
List: 52.67750670600003
๐ŸŒ
DEV Community
dev.to โ€บ iihsan โ€บ time-complexity-analysis-of-python-methods-bigo-notations-for-list-tuple-set-and-dictionary-methods-47l9
Time Complexity Analysis of Python Methods: Big(O) Notations for List, Tuple, Set, and Dictionary Methods - DEV Community
January 15, 2024 - Whether you're working on real-world ... efficient and scalable code. So, understanding the time complexity of your code becomes essential. In this article, we'll break down the Python methods for lists, tuples, sets, and dictionaries....
๐ŸŒ
Finxter
blog.finxter.com โ€บ home โ€บ learn python blog โ€บ python set add()
Python Set add() โ€“ Be on the Right Side of Change
November 2, 2022 - The runtime complexity of the set.add() function is O(1) because Pythonโ€™s set data structure is implemented as a hash table and you can expect lookup, insert, and delete operations to have constant runtime complexity.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ time-complexity-for-adding-element-in-python-set-vs-list
Time Complexity for Adding Element in Python Set vs List - GeeksforGeeks
December 19, 2024 - The average-case time complexity is O(n), where n is the number of elements in the list. In this article, we will see compare different scenarios in which we ... Given a set and list, the task is to write a python program to check if any set ...
๐ŸŒ
Quora
quora.com โ€บ Why-do-sets-in-Python-have-an-algorithmic-complexity-of-O-1
Why do sets in Python have an algorithmic complexity of O(1)? - Quora
Answer (1 of 6): A hash table has expected time complexity for insertion, deletion, and membership checking that is constant in the number of entries being stored. Pythonโ€™s set is built on a hash table implementation. But this conceals some assumptions which can be violated in practice. The con...
๐ŸŒ
Medium
binarybeats.medium.com โ€บ python-set-data-structure-methods-use-time-and-space-complexity-366b8c408345
Python Set Data Structure: Methods, Use, Time, and Space Complexity | by Binary Beats | Medium
April 22, 2023 - Counting distinct elements โ€” You may need to count the number of distinct elements in a list or array. Using a set to store the elements and then getting the size of the set can quickly give you the count. The time and space complexity of set methods can vary depending on the operation being performed.
๐ŸŒ
Quora
quora.com โ€บ How-does-searching-in-a-set-take-O-1-time
How does searching in a set take O(1) time? - Quora
Answer (1 of 4): the Searching performed on an unordered_set takes O(1) time. The reason that it uses hashing in its soul. It uses a hash function to determine a hash for all the inputs and so all the elements can be uniquely identified using a hash value. The lookup in a hash table is O(1) opera...
๐ŸŒ
Python Morsels
pythonmorsels.com โ€บ time-complexities
Python Big O: the time complexities of different data structures in Python - Python Morsels
April 16, 2024 - For example, sets are faster at key lookups than lists, but they have no ordering. Dictionaries are just as fast at key lookups as sets and they maintain item insertion order, but they require more memory. In day-to-day Python usage, time complexity tends to matter most for avoiding loops within ...