Possible Duplicate:
Cost of len() function
How Python calculates length of a list(using len()
function )?Does it go through a for
or while
loop to do the same or it has some internal variable that stores the length of the list ?
Possible Duplicate:
Cost of len() function
How Python calculates length of a list(using len()
function )?Does it go through a for
or while
loop to do the same or it has some internal variable that stores the length of the list ?
Yes, CPython lists have an internal variable for the length.
It's called ob_size
; all variable-sized objects have it.
It uses an internal variable that stores the length of the list (as do all other variable-length object types in Python). So len() is an O(1) operation regardless of the size of the list (i.e. it runs in constant time).
Here's the implementation of len() for lists, here's the Py_SIZE macro it calls, and here's the declaration of ob_size that Py_SIZE uses.
a = range(10)
b = range(1000000)
timeit len(a) # 85.4 ns
timeit len(b) # 94.4 ns
It doesn't look like a loop.
From python's view, the len()
function calls the class's __len__()
method, which returns the internally known length.