What is __ len __ in python?

It's often the case that the "typical" behavior of a built-in or operator is to call (with different and nicer syntax) suitable magic methods (ones with names like __whatever__) on the objects involved. Often the built-in or operator has "added value" (it's able to take different paths depending on the objects involved) -- in the case of len vs __len__, it's just a bit of sanity checking on the built-in that is missing from the magic method:

>>> class bah(object):
...   def __len__(self): return "an inch"
... 
>>> bah().__len__()
'an inch'
>>> len(bah())
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'str' object cannot be interpreted as an integer

When you see a call to the len built-in, you're sure that, if the program continues after that rather than raising an exception, the call has returned an integer, non-negative, and <= sys.maxsize -- when you see a call to xxx.__len__(), you have no certainty (except that the code's author is either unfamiliar with Python or up to no good;-).

Other built-ins provide even more added value beyond simple sanity checks and readability. By uniformly designing all of Python to work via calls to builtins and use of operators, never through calls to magic methods, programmers are spared from the burden of remembering which case is which. (Sometimes an error slips in: until 2.5, you had to call foo.next() -- in 2.6, while that still works for backwards compatibility, you should call next(foo), and in 3.*, the magic method is correctly named __next__ instead of the "oops-ey" next!-).

So the general rule should be to never call a magic method directly (but always indirectly through a built-in) unless you know exactly why you need to do that (e.g., when you're overriding such a method in a subclass, if the subclass needs to defer to the superclass that must be done through explicit call to the magic method).

  • Syntax
  • Background len()
  • Example Custom __len__()
  • Default __len__() Implementation
  • What’s the Difference Between len(x) and x.__len__()?
  • Where to Go From Here?

Syntax

object.__len__(self)

The Python __len__ method returns a positive integer that represents the length of the object on which it is called. It implements the built-in len() function. For example, if you call len(x) an object x, Python internally calls x.__len__() to determine the length of object x.

We call this a “Dunder Method” for “Double Underscore Method” (also called “magic method”). To get a list of all dunder methods with explanation, check out our dunder cheat sheet article on this blog.

💡 Useful Knowledge: If the __bool__() dunder method is not defined, Python internally returns __len__() != 0 to determine whether the object’s associated Boolean value is True or False.

Background len()

Python’s built-in function len() returns the length of the given string, array, list, tuple, dictionary, or any other iterable.

The type of the return value is an integer that represents the number of elements in this iterable.

Python len() – A Simple Guide

Before we learn more about the __len__() dunder method, let’s have a look at a couple of basic len() examples:

>>> friends = ['Alice', 'Bob', 'Carl', 'Ann']
>>> len(friends)
4
>>> friends.extend([1, 2, 3])
>>> len(friends)
7
>>> len('hello world')
11
>>> len('hi')
2
>>> len((1, 2, 3))
3
>>> len({42, 21})
2
>>> age = {'Alice': 18, 'Bob': 21}
>>> len(age)
2
>>> age['Carl'] = 33
>>> len(age)
3

Example Custom __len__()

In the following example, you create a custom class Data and overwrite the __len__() method so that it returns a dummy number.

class Data:
    def __len__(self):
        return 42


a = Data()

print(len(a))
# 42

print(bool(a))
# True    --> Because 42 != 0

If you hadn’t defined the __len__() method, Python would’ve raised an error:

Default __len__() Implementation

If you call len(x) on an object on which the x.__len__() dunder method is not defined, Python will raise a TypeError: object of type '...' has no len(). To fix this error, simply define the __len__() method in the class definition before calling len() on an object.

class Data:
    pass


a = Data()
print(len(a))

Here’s the error message:

Traceback (most recent call last):
  File "C:\Users\xcent\Desktop\code.py", line 7, in 
    print(len(a))
TypeError: object of type 'Data' has no len()

What’s the Difference Between len(x) and x.__len__()?

The result of len(x) and x.__len__() is the same: both return the number of elements in the object, i.e., more generally, its length.

Have a look at this example:

>>> len([1, 2, 3])
3
>>> [1, 2, 3].__len__()
3

The difference between len(x) and x.__len__() is only syntactical sugar. The former built-in function calls the latter method internally to implement the correct behavior. So, there’s no semantic difference between both ways to obtain the length of an object.

References:

  • https://docs.python.org/3/reference/datamodel.html

Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!

What is __ len __ in python?

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.

To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.

His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.

What is __ method in Python?

The Python interpreter modifies the variable name with ___. So Multiple times It uses as a Private member because another class can not access that variable directly. The main purpose for __ is to use variable /method in class only If you want to use it outside of the class you can make it public.

What does __ len __ mean in Python?

Python __len__() Function Syntax Syntax: object.__len__() object: It is the object whose length is to be determined.

What is __ len __( self in Python?

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.

What term can describe the built

Well, len(s) is a built-in Python method which returns the length of an object. Now __len__() is a special method that is internally called by len(s) method to return the length of an object.