2

So a list object does not have a simple length attribute len but rather the "magic" __len__(). Why is it preferred to use the function len() on a list rather than its attribute? Does the function len() not simply query __len__()? Why that detour and not have my_list.len()?

Martin R
  • 219
  • 1
  • 2
  • 7
  • 1
    See https://stackoverflow.com/questions/496009/is-there-any-case-where-lensomeobj-does-not-call-someobjs-len-function/497096#497096 – frostshoxx Apr 19 '18 at 20:48
  • Possible duplicate of [Is there any case where len(someObj) does not call someObj's \_\_len\_\_ function?](https://stackoverflow.com/questions/496009/is-there-any-case-where-lensomeobj-does-not-call-someobjs-len-function) – Pintang Apr 19 '18 at 20:49
  • https://stackoverflow.com/questions/16249418/how-to-python-count-list-length – Sumit Jha Apr 19 '18 at 20:50
  • 1
    [You should only ask practical, answerable questions based on actual problems that you face.](https://stackoverflow.com/help/on-topic) ["Why?" questions on language design do not fit this criteria.](https://meta.stackexchange.com/questions/170394/what-is-the-rationale-for-closing-why-questions-on-a-language-design) – Charles Duffy Apr 19 '18 at 21:04

1 Answers1

12

It might be helpful to think of __len__ as a method you can customize for any object. Part of the reason for the len function vs using .__len__() or .len() is that python was intended to be a language that is easy to learn. For a beginner programmer, understanding that you use the length function to get the length of a list seems very intuitive to me.

For example:

class MyObject:
     def __len__(self):
          return 100

a = MyObject()
assert len(a) == 100

So it's just a construct of all python objects that you can set how length is calculated. This example isn't useful, but perhaps if you had a Circle object, you might want length to be it's Circumference, ie.

 class Circle:
     def __init__(self, radius):
         self.radius = radius

     def __len__(self):
         return 3.14 * self.radius * 2

A benefit of having len as a function as well as a method is the ability to map-filter-reduce len onto arrays. It is very easy to write:

map(len, [[1, 2], [4, 5, 6]])

However, if you really think that .len() is an attractive way to present the length of an object, you could just add a method.

class MyObject:
    def __len__(self):
        return 10
    def len(self):
        return len(self)
Rob
  • 3,333
  • 5
  • 28
  • 71