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.

Syntax:

len(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.

Exampes:

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

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:

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