list.__len__() or len(list)

Hrvoje Niksic hniksic at xemacs.org
Wed May 14 03:01:47 EDT 2008


"Ian Kelly" <ian.g.kelly at gmail.com> writes:

> On Tue, May 13, 2008 at 5:57 PM, Nikhil <mnikhil at gmail.com> wrote:
>>  __len__() is a built-in function of the list object and is updated along
>> with the list object elements and will be useful incase the list is very
>> huge.
>>
>>  len() is an external method again, which may require the processing cycles
>> again.
>
> The purpose of obj.__len__() is to implement len(obj), which simply
> calls it.  So obj.__len__() may be faster, but only marginally.

Have you tried it?  __len__ is in fact marginally slower because it
involves a dict lookup, whereas the built-in len() knows how to cheat
and invoke __len__ through a slot in the C type struct very
efficiently.

$ python -m timeit -s 'l=[1, 2, 3]' 'len(l)'
1000000 loops, best of 3: 0.24 usec per loop
$ python -m timeit -s 'l=[1, 2, 3]' 'l.__len__()'
1000000 loops, best of 3: 0.347 usec per loop



More information about the Python-list mailing list