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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With