The complexity of in depends entirely on what L is. e in L will become L.__contains__(e).

See this time complexity document for the complexity of several built-in types.

Here is the summary for in:

  • list - Average: O(n)
  • set/dict - Average: O(1), Worst: O(n)

The O(n) worst case for sets and dicts is very uncommon, but it can happen if __hash__ is implemented poorly. This only happens if everything in your set has the same hash value.

Answer from Andrew Clark on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python › time-complexity-of-in-operator-in-python
Time Complexity of In Operator in Python - GeeksforGeeks
July 23, 2025 - When you use the in operator to check if an element exists in a list, Python performs a linear search which means it iterates through each element of the list until it finds a match or reaches the end of the list. ... The time complexity is O(n) ...
Discussions

Python string 'in' operator implementation algorithm and time complexity - Stack Overflow
I am thinking of how the in operator implement, for instance >>> s1 = 'abcdef' >>> s2 = 'bcd' >>> s2 in s1 True In CPython, which algorithm is used to implement the string More on stackoverflow.com
🌐 stackoverflow.com
time complexity - 'in' operator functionality in python - Stack Overflow
I needed to remove the characters in string1 which are present in string2. Here string1 and string2 have only the lower case characters a-z with given condition that the length of string1 will be g... More on stackoverflow.com
🌐 stackoverflow.com
Python "in" operator time complexity on range() - Stack Overflow
I have the following function: def foo(length, num): return num in range(length) What's the time complexity of this function? Noting that range() creates a Range object on Python 3, will the time More on stackoverflow.com
🌐 stackoverflow.com
Time complexity of Counters in Python
And if so, wouldn't the time complexity of checking if a key is in a dictionary be O(n) Your link says O(1) on average, assuming a good enough hash function. More on reddit.com
🌐 r/learnpython
10
5
July 30, 2021
🌐
Reddit
reddit.com › r/learnpython › what is the time complexity of the “in” operation
r/learnpython on Reddit: What is the time complexity of the “in” operation
September 1, 2021 -

I’m not the biggest python user. But I was looking at a friends code yesterday and they had something like:

For x in (list of 40000)

For y in (list of 2.7 million)

  If x = y 

     Append something 

This was obviously super slow so they changed it to something like:

For x in (list of 2.7 million)

If y in (list of 40000)

  Append something 

This moved much faster. I get the point of one for loop being faster than two, but what is that “in” exists function doing that makes it so much faster. I always thought that to check if something exists is O(n) which shouldn’t be faster. Also this was for ML purposes so they were likely using numpy stuff.

🌐
Note.nkmk.me
note.nkmk.me › home › python
The in Operator in Python (for List, String, Dictionary) | note.nkmk.me
May 9, 2023 - di = d.items() %%timeit for i in range(n_large): (i, i) in di # 1.18 ms ± 26.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) ... The in keyword is also used in for statements and list comprehensions.
🌐
UCI
ics.uci.edu › ~pattis › ICS-33 › lectures › complexitypython.txt
Complexity of Python Operations
Implementation 1: N*O(1) + N*O(N) = O(N) + O(N**2) = O(N**2) Implementation 2: N*O(N) + N*O(1) = O(N**2) + O(N) = O(N**2) Implementation 3: N*O(Log N) + N*O(Log N) = O(NLogN) + O(NLogN) = O(NLogN) Note N*O(...) is the same as O(N)*O(...) which is the same as O(N * ...) Here, Implementation ...
🌐
Cdotson
cdotson.com › 2015 › 07 › python-in-operator-theoretical-vs-actual-time-complexity
The Python “in” Operator – Theoretical vs Actual Time Complexity – Chad Dotson
Theoretically a set, frozenset or dictionary should be the fastest (and equivalent) forms of storage for this operation. However, what I’ve found is that on some systems the set is faster and on others dict is faster. This difference maybe very important if your writing real-time or close to real-time software. So where am I going with this? Python has published the expected time complexities of their collection types.
🌐
Quora
quora.com › Does-the-in-operator-while-searching-keys-in-Python-Dictionary-take-O-1-If-yes-how
Does the 'in' operator while searching keys in Python Dictionary take O(1)? If yes, how? - Quora
Answer (1 of 2): Yes. The way it works is by using a Hash Table as the underlying implementation for Python dictionaries. Hash tables have O(1) insertion, O(1) deletion, and O(1) search. Basically, they’re miraculous and you should worship them as your savior because they make so many things WAY ...
Find elsewhere
🌐
GitHub
gist.github.com › Gr1N › 60b346b5e91babb5efac
Complexity of Python Operations · GitHub
Complexity of Python Operations. GitHub Gist: instantly share code, notes, and snippets.
🌐
CodeGenes
codegenes.net › blog › what-is-the-time-complexity-of-in-for-keys-python
Understanding the Time Complexity of the `in` Operator for Keys in Python — codegenes.net
The running time of the algorithm grows quadratically with the input size. In Python, dictionaries are implemented using hash tables. When you use the in operator to check if a key exists in a dictionary, the time complexity is O(1) on average.
🌐
GeeksforGeeks
geeksforgeeks.org › complexity-cheat-sheet-for-python-operations
Complexity Cheat Sheet for Python Operations - GeeksforGeeks
December 13, 2024 - This cheat sheet is designed to help developers understand the average and worst-case complexities of common operations for these data structures that help them write optimized and efficient code in Python. Python's list is an ordered, mutable sequence, often implemented as a dynamic array. Below are the time complexities for common list operations:
🌐
Python
wiki.python.org › moin › TimeComplexity
TimeComplexity - Python Wiki
The average case for an average value of k is popping the element the middle of the list, which takes O(n/2) = O(n) operations. [3] = For these operations, the worst case n is the maximum size the container ever achieved, rather than just the current size. For example, if N objects are added ...
🌐
A Girl Among Geeks
agirlamonggeeks.com › home › what is the time complexity of using ‘in’ for keys in python dictionaries?
What Is the Time Complexity of Using 'in' for Keys in Python Dictionaries?
July 4, 2025 - This design allows for efficient average-case lookups, which is a critical reason why dictionaries are widely used for membership tests. The average time complexity of the `in` operator for dictionary keys is O(1), meaning that it typically takes constant time regardless of the number of keys ...
Top answer
1 of 3
7

in does not necessarily use loops behind the scenes. For example:

r = range(100000000000)
print(333 in r)  # prints True immediately without looping

If you were to loop r it will take quite a long time, so clearly that doesn't happen.

in basically calls (behind the scenes) the object's __contains__ method. For some iterators it will in fact "loop" through everything but that's not always the case.

This example is basically the same as calling:

r.__contains__(333)

As pointed out in comments - the str objects specifically have a smarter algorithm than just plain loops, as you can see here

Also see example answer here

And see the documentation here

Because the real world scenario would probably mean that string1 can be arbitrarily long, but the characters to be removed would be a finite and small set, it will probably be much more efficient to just add up all the characters that aren't in string2. Something like this:

def removeChars (string1, string2):
    result = ''
    for char in string1:
        if char not in string2:
            result += char
    return result

This will involve looping over string1 just once, but multiple checks against string2 using in. This can be further simplified (to avoid += loop over the result):

def removeChars (string1, string2):
    return ''.join(char for char in string1 if char not in string2)
2 of 3
2

When in is equivalent to a loop, it has to 'walk' the iterator and compare each item in turn.

This means each loop is O(n), so for 2 levels this is O(n²)

https://wiki.python.org/moin/TimeComplexity

Note that you actually have 3 loops here - since your replace will also walk through the string.

Since replace doens't raise any errors if char isn't found, it is simpler to just do this without first testing char in string1.

🌐
DEV Community
dev.to › williams-37 › understanding-time-complexity-in-python-functions-5ehi
Understanding Time Complexity in Python Functions - DEV Community
October 25, 2024 - Finding the length of a list, dictionary, or set is a constant time operation. List Comprehensions: [expression for item in iterable] → O(n) The time complexity of list comprehensions is linear, as they iterate through the entire iterable.
🌐
Real Python
realpython.com › python-in-operator
Python's "in" and "not in" Operators: Check for Membership – Real Python
January 26, 2025 - So, the membership operator will have to check all the values before getting a final result. As you already know, when the in operator searches for a value in a list, it uses an algorithm with a time complexity of O(n).
🌐
Finxter
blog.finxter.com › home › learn python blog › complexity of python operations
Complexity of Python Operations - Be on the Right Side of Change
May 29, 2020 - In this tutorial, you’ll learn the runtime complexity of different Python operations. Then, you’ll learn how to calculate the complexity of your own function by combining the complexity classes of its constituents. This is called “static analysis” The tutorial is loosely based on (source) but it extends it significantly with more practical examples, interactive snippets, ... Read more
Top answer
1 of 1
16

In python-3.x a range(..) is an object, it does not construct a list. If you perform member checks with an int as item, then it can do that quite fast. The algorithm is a bit complicated, since there are both positive and negative steps. You can look it up on [GitHub]. A simple algorithm with a positive step count (c > 0) for x in range(a, b, c) is something like:

x ≥ a ∧ x < b ∧ mod(x-a, c) = 0.

For a negative step count (c < 0) is is quite similar:

x ≤ a ∧ x > b ∧ mod(x-a, c) = 0.

If we consider the comparisons to be done in O(1) and calculating the modulo as well, it is an O(1) algorithm. In reality for huge numbers, it scales in the number of digits of the numbers, so it is an O(log n) algorithm.

This however only works for ints. Indeed, in case you use floats, complex, other numerical or non-numerical types, it does not perform the above calculations. It will then fall back on iterating over the range(..) object. Which of course can take considerable time. If you have a range of a million elements, it will thus iterate over all these elements and eventually reach the end of the range, and return False, or find a match, and return True. In the future, perhaps some extra functionality can be implemented for some numerical types, but one can not do this in general, since you can define your own numerical type with an equality operation that works differently.

In python-2.x, range(..) is a function that returns a list. Indeed:

>>> range(15)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
>>> type(range(15))
<type 'list'>

In order to check if an element is a member of a list, it will iterate over the list, and check equality for all items until it finds an element that is equal, or the list is exhausted. If we consider checking if two items are equal to be constant time, then this takes linear time O(n). In reality for huge numbers, checking if two numbers are equal, scales linear with the number of "digits", so O(log m) with m the value of that number.

python-2.x has an xrange(..) object as well, but this does not check for membership with the above demonstrated trick.

🌐
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 - The IN Operator uses linear search with a time complexity of O(n). Thanks for reading! Feel free to like, comment, and share if you find this article valuable. You can check my other articles as well: Mastering Metaclasses in Python using real-life ...
🌐
Intellipaat
intellipaat.com › community › 77012 › complexity-of-in-operator-in-python
Complexity of *in* operator in Python - Intellipaat Community
June 15, 2023 - What is the Complexity of the in administrator in Python? Is it theta(n)? Is it equivalent to the ... True return False Here, L is a list.