The len() function is used to calculate the length of a sequence, such as a string, list, dictionary, range, etc.

The length of an  iterable object is mostly used to refer to the number of elements it contains. For example a list with three items such as [1, 2, 3] has a length of 3, similarly, string like "Hello" has a length of 5, indicating the number of characters in the string. However, for user defined objects, the length can mean something else.

The function takes a single argument, the object and always returns an integer representing the length of the object.



The object used as the arguments needs to have defined the__len__() method, otherwise a TypeError will be raised . This method is responsible for determining the length of the object and should return an integer representing the number of elements or items in the object  or its length based on its internal logic and structure. By default, all the builtin sequences such as lists, tuples dictionaries, sets, etc, have the __len__() method defined.


L = []
L1 = [1, 2, 3]
len("Hello, World!")
len(('Python', 'PHP', 'CSS', 'Java', 'C++', 'Ruby'))
len({3, 5, 7, 11})
len({1: 'one', 2: "two"})

As we said earlier, a TypeError will be raised if you call len() with an object that does not have the __len__() method defined. Examples:

//TypeError: object of type 'int' has no len()
//TypeError: object of type 'bool' has no len()
//TypeError: object of type 'builtin_function_or_method' has no len()