In Python, len
is a function to get the length of a collection by calling an object's __len__
method:
def len(x): return x.__len__()
So I would expect direct call of __len__()
to be at least as fast as len()
.
import timeit setup = ''' ''' print (timeit.Timer('a="12345"; x=a.__len__()', setup=setup).repeat(10)) print (timeit.Timer('a="12345"; x=len(a)', setup=setup).repeat(10))
Demo link
But results of testing with the above code shows len()
to be faster. Why?
Internal Working of the len() Function in PythonIt takes absolutely no time, and equal time, in calculating the lengths of iterable data structures(string, array, tuple, etc.), irrespective of the size or type of data. This obviously implies O(1) time complexity.
Python len() The len() function returns the number of items (length) in an object.
The fact that len is a function means that classes cannot override this behaviour to avoid the check. As such, len(obj) gives a level of safety that obj. len() cannot.
The function len() is one of Python's built-in functions. It returns the length of an object. For example, it can return the number of items in a list. You can use the function with many different data types.
The builtin len()
function does not look up the .__len__
attribute. It looks up the tp_as_sequence
pointer, which in turn has a sq_length
attribute.
The .__len__
attribute on built-in objects is indirectly mapped to the same slot, and it is that indirection (plus the attribute lookup) that takes more time.
For Python-defined classes, the type
object looks up the .__len__
method when the sq_length
is requested.
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