len function in Python


Posted: 2012/12/22 01:28:51 | Source | More posts about Python

This post is for my friends who become really confused with len() function and __len__() special method.

len(obj) is a builtin function which returns the length of an object. The obj argument can be either a sequence (lists, tuple or string) or a mapping (dictionary).

Now object.__len__(self) is the special method which is called in the implementation of len() function. For a class you define object.__len__(self) function and compute the length, then calling len(obj) on the instance gives you the length.

len() also does sanity checking on top of object.__len__(self) output.

    >>> class Foo(object):
    ...   def __len__(self): return '1'
    ... 
    >>> obj = Foo()
    >>> obj.__len__()
    '1'
    >>> len(obj)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: an integer is required
comments powered by Disqus
Contents © 2004-2014 Kushal Das - Powered by Shonku