len(obj) simply calls obj.__len__():

>>> [1, 2, 3, 4].__len__()
4

It is therefore not correct to say that len() is always O(1) -- calling len() on most objects (e.g. lists) is O(1), but an arbitrary object might implement __len__ in an arbitrarily inefficient way.

max(obj) is a different story, because it doesn't call a single magic __max__ method on obj; it instead iterates over it, calling __iter__ and then calling __next__. It does this n times (and also does a comparison each time to track the max item it's seen so far), so it must always be at least O(n). (It can be slower if __next__ or the comparison methods are slow, although that would be very unusual.)

For either of these, we don't count the time it took to build the collection as part of the cost of calling the operation itself -- this is because you might build a list once and then call len() on it many times, and it's useful to know that the len() by itself is very cheap even if building the list was very expensive.

Answer from Samwise on Stack Overflow
Top answer
1 of 3
8

len(obj) simply calls obj.__len__():

>>> [1, 2, 3, 4].__len__()
4

It is therefore not correct to say that len() is always O(1) -- calling len() on most objects (e.g. lists) is O(1), but an arbitrary object might implement __len__ in an arbitrarily inefficient way.

max(obj) is a different story, because it doesn't call a single magic __max__ method on obj; it instead iterates over it, calling __iter__ and then calling __next__. It does this n times (and also does a comparison each time to track the max item it's seen so far), so it must always be at least O(n). (It can be slower if __next__ or the comparison methods are slow, although that would be very unusual.)

For either of these, we don't count the time it took to build the collection as part of the cost of calling the operation itself -- this is because you might build a list once and then call len() on it many times, and it's useful to know that the len() by itself is very cheap even if building the list was very expensive.

2 of 3
6

Let's check it:

import time
from matplotlib import pyplot as plt
import numpy as np


def main():
    a = []
    data = []
    for i in range(10_000):
        a.append(i)
        ts_len = time.time()
        _ = len(a)
        te_len = time.time()

        ts_max = time.time()
        _ = max(a)
        te_max = time.time()

        ts_min = time.time()
        _ = min(a)
        te_min = time.time()

        data.append([i, te_len - ts_len, te_max - ts_max, te_min - ts_min])

    data = np.array(data)
    plt.plot(data[:, 0], data[:, 1], "-r", label="len")
    plt.plot(data[:, 0], data[:, 2], "--g", label="max")
    plt.plot(data[:, 0], data[:, 2], ".b", label="min")
    plt.title("Len/max/min")
    plt.xlabel("Size of the list")
    plt.ylabel("Time elapsed (s)")
    plt.legend()
    plt.show()


if __name__ == '__main__':
    main()

🌐
GeeksforGeeks
geeksforgeeks.org › python › complexity-of-len-with-regard-to-sets-and-lists
Complexity Of Len() With Regard To Sets And Lists - GeeksforGeeks
July 23, 2025 - The length attribute is maintained and updated in constant time as elements are added or removed. ... The space complexity of the len() operation on lists is also constant. It doesn't require additional space proportional to the size of the list. The length attribute is a fixed-size attribute associated with the list object. Sets in Python are implemented as hash tables.
Discussions

python - Cost of len() function - Stack Overflow
As time curves so does language and with it asthetic (slang) why we have to rewrite old English and etc 2026-03-16T16:38:51.367Z+00:00 ... Calling len() on those data types is O(1) in CPython, the official and most common implementation of the Python language. Here's a link to a table that provides the algorithmic complexity ... More on stackoverflow.com
🌐 stackoverflow.com
Why is the complexity of len(list) O(1)?
len is an O(1) because in your RAM, lists are stored as tables (series of contiguous addresses). To know when the table stops the computer needs two things : length and start point. That is why len() is a O(1), the computer stores the value, so it just needs to look it up. More on reddit.com
🌐 r/learnpython
6
7
October 8, 2017
python - Time complexity of the Neighbors function - Bioinformatics Stack Exchange
I implemented the following find_neighbors_with_expected_hamming_distance function that generates all k-mers of Hamming distance at most d from the given Pattern. from .Hamming_Distance import More on bioinformatics.stackexchange.com
🌐 bioinformatics.stackexchange.com
Performance of length(::String)
Hi! I’ve noticed that length(::String) isn’t a cheap operation in Julia, since it requires to iterate the string. In fact, it’s more expensive than Python len(str), even for unicode strings. Also, length(::String) is slower in Julia 0.7 than in Julia 0.6: Julia 0.6.4 julia> const ... More on discourse.julialang.org
🌐 discourse.julialang.org
0
2
July 26, 2018
🌐
Medium
medium.com › @hamzaehsankhan › why-len-list-has-a-time-complexity-of-o-1-a-dive-into-cpython-cbed75c38b54
Why len(list) has a time-complexity of O(1)? — A dive into CPython | by Hamza Ehsan Khan | Medium
July 13, 2023 - This in-built function is not at the mercy of the size of the list. Whether your list contains 1 element or 1000, as per the default implementation of Python (CPython), the time-complexity is O(1).
🌐
Python
wiki.python.org › moin › TimeComplexity
TimeComplexity
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).
🌐
DigitalOcean
digitalocean.com › community › tutorials › find-the-length-of-a-list-in-python
How to find the length of a list in Python | DigitalOcean
July 25, 2025 - The len() function has a time complexity of O(1), which means its execution time is constant. It takes the same amount of time to complete regardless of the size of the list. This is possible because Python’s list objects are implemented in C as a structure (PyListObject).
Find elsewhere
🌐
Quora
quora.com › What-are-the-time-complexity-considerations-of-lists-in-Python
What are the time complexity considerations of lists in Python? - Quora
in a Python list it holds references to objects in contiguous memory; and since those references are the same size regardless of type, indexing is constant time - literally when you do: ... The += operator calls the __iadd__ method of a class. In case of a list, this is equivalent to calling extend, which has a time complexity [math]O(len of extension)[/math]. I’m not really sure about the space complexity, but I strongly suspect it’s simply [math]O(1)[/math].
🌐
Tutorialspoint
tutorialspoint.com › python › list_len.htm
Python List len() Method
Therefore, when this method is called, it will not command the interpreter to traverse the list; instead the interpreter is asked to print the counter value that exists already. Hence, the time complexity of the len() method is O(1). Following is the syntax for the Python List len() method −
🌐
GeeksforGeeks
geeksforgeeks.org › python › internal-working-of-the-len-function-in-python
Internal Working of the len() Function in Python - GeeksforGeeks
July 2, 2020 - Thus when you call the len() function, you do not give the interpreter the command to find the length by traversing, but rather you ask the interpreter to print a value that is already stored. Hence, len() function in Python runs in O(1) complexity.
🌐
Reddit
reddit.com › r/learnpython › why is the complexity of len(list) o(1)?
r/learnpython on Reddit: Why is the complexity of len(list) O(1)?
October 8, 2017 -

I was looking at the time complexity of different list operations and the "get length" operation has constant time O(1). Why is that? I would understand it if lists could only store a single type of object (e.g. only integers or characters), but since lists can hold objects of a different size I don't understand how the len() function has O(1) complexity.

🌐
Real Python
realpython.com › len-python-function
Using the len() Function in Python – Real Python
November 16, 2024 - You can read more about using object-oriented programming and defining classes in Object-Oriented Programming (OOP) in Python. ... You’ve explored how to use len() to determine the number of items in sequences, collections, and other data types that hold several items at a time, such as NumPy arrays and pandas DataFrames.
🌐
Copahost
copahost.com › home › len python: complete guide to python’s len() function
Len Python: complete guide to Python's len() function - Copahost
August 5, 2023 - While most Python implementations of the len function have O(1) time complexity for fixed-size objects, some implementations may have O(n) time complexity for variable-size objects such as lists or dictionaries.
🌐
Scaler
scaler.com › home › topics › python length of list
Python Length of List - Scaler Topics
May 4, 2023 - The length_hint() method in python works the same way as len() method, it applies to more data types than len() method. Also, it does not always return the exact number of elements in the list. Naive method uses a loop and a counter. It visits each element in the list and increments the counter. It is easy to implement and doesn't require pre-defined functions. Time complexity of the Naive method is O(n) whereas that of len() and length_hint() is O(1).
Top answer
1 of 1
2

Let's first establish a lower bound on any solution:

Given a hamming distance $D$ and an input pattern $P$ of length $N$, there are $\sum_{k=0}^D{N \choose k} 3^k$ other strings within hamming distance $D$ of $P$. Of course in the worst case, when $D=N$, there are $4^n$ possible strings. We can also get a closed bound on the number of solutions. We can show that the sum of the first $D$ binomial coefficients for a fixed $N$ is bounded by ${N \choose D} {N-(D-1) \over N-(2D-1)}$ as shown here. Therefore we have the following closed upper bound on the number of strings within hamming distance $D$ of some pattern of length $N$

$$ \sum_{k=0}^D{N \choose k} 3^k \leq {N \choose D} {3^D (N-(D-1)) \over N-(2D-1)} \leq \left(\frac{3N}{D}\right)^D {N-(D-1) \over N-(2D-1)} $$

However, for your approach, you are going through recursively, so when the subproblem is on strings within $D$ of the suffix of length $n$, you have $\sum_{k=0}^D{n \choose k} 3^k$ of these. Given that you have $N$ subproblems (suffixes), at first glance it does indeed look like you have roughly $\sum_{n=1}^N\sum_{k=0}^D{n \choose k} 3^k$ iterations of the innermost for loop. However, in that for loop, you are also computing the Hamming Distance function, which is $O(n)$. This means that you have roughly

$$ \sum_{n=1}^Nn\sum_{k=0}^D{n \choose k} 3^k $$

computations.

I would suggest finding a way to get rid of having to compute the hamming function. Since you are constructing the sequences yourself, you can keep track of each sequences hamming distance from the pattern during construction.

🌐
Codecademy Forums
discuss.codecademy.com › frequently asked questions
Python Challenge - Find Xth Number In Order - Page 2 - Frequently Asked Questions - Codecademy Forums
June 5, 2022 - You wrote that the O(n) time complexity would perform better than Python’s built in sort function. However, when I searched the time complexity of the .sort() function, it came up to be O(n log n) in time and O(n) in space.
🌐
Julia Programming Language
discourse.julialang.org › general usage › performance
Performance of length(::String) - Performance - Julia Programming Language
July 26, 2018 - Hi! I’ve noticed that length(::String) isn’t a cheap operation in Julia, since it requires to iterate the string. In fact, it’s more expensive than Python len(str), even for unicode strings. Also, length(::String) is sl…
🌐
Quora
quora.com › Can-I-find-the-len-function-on-Python-GitHub-I-tried-searching-the-code-in-the-repository-but-the-len-function-is-not-defined-there-rather-used-on-different-places-Why-is-that
Can I find the len() function on Python GitHub? I tried searching the code in the repository, but the len(), function is not defined there, rather used on different places. Why is that? - Quora
Answer (1 of 2): It sounds like you want to find the underlying code that expresses how Python’s len function calculates its integer result when given an object, list, or any other type of value. Both cPython and pypy are Python interpreters with their source code on github but I’ll assume you’r...
🌐
Dataquest Community
community.dataquest.io › q&a › dq courses
34-10 Function Time Complexity - DQ Courses - Dataquest Community
December 2, 2019 - In the mission Algorithms we are asked to find time complexities of the two following functions. I think that function 1 has a constant time complexity (find the length of the list) and function 2 has linear time complex…