Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Python's 'len' function faster than the __len__ method?

Tags:

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?

like image 255
Ωmega Avatar asked Nov 30 '13 16:11

Ωmega


People also ask

How fast is Python LEN function?

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.

What does __ len __ mean in Python?

Python len() The len() function returns the number of items (length) in an object.

Why is len a function not a method in Python?

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.

Is Len () a function or a method?

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.


Video Answer


1 Answers

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.

like image 162
Martijn Pieters Avatar answered Nov 04 '22 00:11

Martijn Pieters