len() and __len__

Pete Shinners shredwheat at attbi.com
Sun May 26 12:13:36 EDT 2002


Artur Siekielski wrote:
> Is there any difference between len(a) and a.__len__() in Python 2.2?

in certain situations there is no difference, but using len() is preferred 
for a couple reasons.

first, it's not recommended to go calling the __methods__ yourself, they 
are meant to be used by other parts of python.

len() will work on any type of sequence object (lists, tuples, and all). 
__len__ will only work on class instances with a __len__ method.

len() will return a more appropriate exception on objects without length.




More information about the Python-list mailing list