Python len() is a built-in function that returns the length(number of items ) of an object.

python len() functionpyy

Python len() Syntax

len(s)

len() function takes only one parameter as argument.

  • s (required) – object whose length is to be returned.

The parameter can be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).

A TypeError is raised if no argument is supplied or an invalid argument is supplied to the function len().

__len__() method

Many people get confused with the difference between __len__() and len() method.

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.

So, when we call len(s) method, s.__len__() is what actually happening behind the scenes to calculate the length.

The Python len() function can be interpreted as:

def len(s):
    return s.__len__()

Python len() Example

#Python len() with Lists

>>> list1 = []
>>> len(list1)
0

>>> list2 = [1,2,3]
>>> len(list2)
3

#Python len() with Tuples

>>> tuple1 = ()
>>> len(tuple1)
0

>>> tuple2 = (1,2,3)
>>> len(tuple2)
3

#Python len() with Strings

>>> str1 = ''
>>> len(str1)
0

>>> str2 = 'Python'
>>> len(str2)
6

#Python len() with Sets

>>> set1 = {}
>>> len(set1)
0

>>> set2= {1,2,3}
>>> len(set2)
3

#Python len() with custom objects

>>> class Example:
       def __len__(self):
            return 6

>>> obj = Example()
>>> obj.__len__()
6
>>> len(obj)
6