Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Object-Oriented Python Advanced Objects Emulating Built-ins

The difference between dunder len and len()

Kinda confused between dunder len and len(), is dunder len object-oriented while len() is not?

Thanks in advance 😁

1 Answer

Josh Keenan
Josh Keenan
19,652 Points

Well __len__ is len(). When you call the function, it uses that objects __len__ method to evaluate what it should do with this type of object. It was thought that it would be easier using len(a) instead of a.len(), so they got it to work like this. Sorry I don't know as much about this as I should, but I hope this helps!

Great, thanks Josh!

Chris Freeman
Chris Freeman
Treehouse Moderator 68,423 Points

Great answer. Most of the dunder methods are defined to be called by a corresponding built-in function. If one really wanted to have a.len() functionality also work, a len method could be added (though not recommended):

def a:
    def len(self):  # len method called using a.len()
        return len(self)  # call to built-in len() function

So, a.len() calls the len method that, in turn, calls the built-in function len() which would call the __len__ method. The __len__ method might be defined locally or inherited from a standard type. Caution: the line return self.len(self) would cause a recursive stack overflow since the method calls itself. Good luck!!

Thanks for the example Chris, it helped!