list.__len__() or len(list)
Nikhil
mnikhil at gmail.com
Wed May 14 11:07:00 EDT 2008
Christian Heimes wrote:
> Ian Kelly schrieb:
>> The purpose of obj.__len__() is to implement len(obj), which simply
>> calls it. So obj.__len__() may be faster, but only marginally. The
>> reason to prefer len(obj) is that if you inadvertently pass an object
>> that does not implement __len__, you get the more appropriate
>> TypeError rather than an AttributeError.
>
> len(obj) is faster than obj.__len__() for several types like str. In
> general len() is as least as fast __len__(). len() also does some extra
> sanity checks.
>
> python2.5 -m timeit "'abc'.__len__()"
> 1000000 loops, best of 3: 0.453 usec per loop
>
> python2.5 -m timeit "len('abc')"
> 1000000 loops, best of 3: 0.292 usec per loop
>
> Common code paths are already highly optimized. Don't try to be clever
> unless you really understand what happens inside the interpreter. The
> __internal__ methods are called magic methods for a reason. ;)
>
> Christian
>
Thanks for the useful insight.
Then why to have __len__() internal method at all when the built-in
len() is faster?
I heard, in Python3, this internal method is being pruned/renamed to
something else? Can someone please shed light here?
Thanks. Nikhil
More information about the Python-list
mailing list